[teiid-commits] teiid SVN: r2709 - in tags: teiid-parent-7.2.0.Final and 61 other directories.

teiid-commits at lists.jboss.org teiid-commits at lists.jboss.org
Thu Nov 4 23:20:11 EDT 2010


Author: shawkins
Date: 2010-11-04 23:19:55 -0400 (Thu, 04 Nov 2010)
New Revision: 2709

Added:
   tags/teiid-parent-7.2.0.Final/
   tags/teiid-parent-7.2.0.Final/adminshell/pom.xml
   tags/teiid-parent-7.2.0.Final/api/pom.xml
   tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
   tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/teiid-releasenotes.html
   tags/teiid-parent-7.2.0.Final/build/pom.xml
   tags/teiid-parent-7.2.0.Final/cache-jbosscache/pom.xml
   tags/teiid-parent-7.2.0.Final/client/pom.xml
   tags/teiid-parent-7.2.0.Final/common-core/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/connector-file/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/connector-ldap/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/connector-salesforce/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/connector-ws/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/salesforce-api/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/sandbox/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/sandbox/translator-yahoo/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-file/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-jdbc/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-ldap/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-loopback/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/QueryExecutionImpl.java
   tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/TestQueryExecutionImpl.java
   tags/teiid-parent-7.2.0.Final/connectors/translator-ws/pom.xml
   tags/teiid-parent-7.2.0.Final/console/pom.xml
   tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java
   tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/Facet.java
   tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
   tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java
   tags/teiid-parent-7.2.0.Final/console/src/main/resources/META-INF/rhq-plugin.xml
   tags/teiid-parent-7.2.0.Final/documentation/admin-guide/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/admin-guide/src/main/docbook/en-US/content/appendix-a.xml
   tags/teiid-parent-7.2.0.Final/documentation/caching-guide/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/client-developers-guide/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/developer-guide/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/quick-start-example/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/reference/pom.xml
   tags/teiid-parent-7.2.0.Final/engine/pom.xml
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/cache/CacheConfiguration.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/JoinRegion.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/parser/QueryParser.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/resources/org/teiid/query/i18n.properties
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/processor/TestMaterialization.java
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
   tags/teiid-parent-7.2.0.Final/hibernate-dialect/pom.xml
   tags/teiid-parent-7.2.0.Final/jboss-integration/pom.xml
   tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
   tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties
   tags/teiid-parent-7.2.0.Final/metadata/pom.xml
   tags/teiid-parent-7.2.0.Final/pom.xml
   tags/teiid-parent-7.2.0.Final/runtime/pom.xml
   tags/teiid-parent-7.2.0.Final/runtime/src/main/java/org/teiid/transport/SocketConfiguration.java
   tags/teiid-parent-7.2.0.Final/test-integration/common/pom.xml
   tags/teiid-parent-7.2.0.Final/test-integration/db/pom.xml
   tags/teiid-parent-7.2.0.Final/test-integration/pom.xml
Removed:
   tags/teiid-parent-7.2.0.Final/adminshell/pom.xml
   tags/teiid-parent-7.2.0.Final/api/pom.xml
   tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
   tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/teiid-releasenotes.html
   tags/teiid-parent-7.2.0.Final/build/pom.xml
   tags/teiid-parent-7.2.0.Final/cache-jbosscache/pom.xml
   tags/teiid-parent-7.2.0.Final/client/pom.xml
   tags/teiid-parent-7.2.0.Final/common-core/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/connector-file/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/connector-ldap/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/connector-salesforce/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/connector-ws/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/salesforce-api/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/sandbox/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/sandbox/translator-yahoo/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-file/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-jdbc/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-ldap/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-loopback/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/pom.xml
   tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/QueryExecutionImpl.java
   tags/teiid-parent-7.2.0.Final/connectors/translator-ws/pom.xml
   tags/teiid-parent-7.2.0.Final/console/pom.xml
   tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java
   tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/Facet.java
   tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
   tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java
   tags/teiid-parent-7.2.0.Final/console/src/main/resources/META-INF/rhq-plugin.xml
   tags/teiid-parent-7.2.0.Final/documentation/admin-guide/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/admin-guide/src/main/docbook/en-US/content/appendix-a.xml
   tags/teiid-parent-7.2.0.Final/documentation/caching-guide/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/client-developers-guide/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/developer-guide/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/quick-start-example/pom.xml
   tags/teiid-parent-7.2.0.Final/documentation/reference/pom.xml
   tags/teiid-parent-7.2.0.Final/engine/pom.xml
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/cache/CacheConfiguration.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/JoinRegion.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/parser/QueryParser.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
   tags/teiid-parent-7.2.0.Final/engine/src/main/resources/org/teiid/query/i18n.properties
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/processor/TestMaterialization.java
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
   tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
   tags/teiid-parent-7.2.0.Final/hibernate-dialect/pom.xml
   tags/teiid-parent-7.2.0.Final/jboss-integration/pom.xml
   tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
   tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties
   tags/teiid-parent-7.2.0.Final/metadata/pom.xml
   tags/teiid-parent-7.2.0.Final/pom.xml
   tags/teiid-parent-7.2.0.Final/runtime/pom.xml
   tags/teiid-parent-7.2.0.Final/runtime/src/main/java/org/teiid/transport/SocketConfiguration.java
   tags/teiid-parent-7.2.0.Final/test-integration/common/pom.xml
   tags/teiid-parent-7.2.0.Final/test-integration/db/pom.xml
   tags/teiid-parent-7.2.0.Final/test-integration/pom.xml
Log:
[maven-release-plugin]  copy for tag teiid-parent-7.2.0.Final

Copied: tags/teiid-parent-7.2.0.Final (from rev 2706, branches/7.2.x)

Deleted: tags/teiid-parent-7.2.0.Final/adminshell/pom.xml
===================================================================
--- branches/7.2.x/adminshell/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/adminshell/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,69 +0,0 @@
-<?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">
-	<parent>
-		<artifactId>teiid-parent</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>teiid-adminshell</artifactId>
-	<name>Adminshell</name>
-	<description>Adminshell for Teiid</description>
-	<dependencies>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-			<scope>provided</scope>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-			<type>test-jar</type>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-			<scope>provided</scope>
-		</dependency>
-		<dependency>
-			<groupId>org.codehaus.groovy</groupId>
-			<artifactId>groovy-all</artifactId>
-			<version>1.7.2</version>
-		</dependency>
-		<dependency>
-			<groupId>junit</groupId>
-			<artifactId>junit</artifactId>
-			<version>3.8.1</version>
-		</dependency>
-		<dependency>
-			<groupId>junit</groupId>
-			<artifactId>junit</artifactId>
-			<version>4.4</version>
-			<scope>test</scope>
-		</dependency>
-        <dependency>
-            <groupId>jline</groupId>
-            <artifactId>jline</artifactId>
-            <version>0.9.94</version>
-            <scope>compile</scope>
-            <exclusions>
-                <exclusion>
-                    <groupId>junit</groupId>
-                    <artifactId>junit</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>org.fusesource.jansi</groupId>
-            <artifactId>jansi</artifactId>
-            <version>1.2.1</version>
-            <scope>compile</scope>
-        </dependency>
-        <dependency>
-            <groupId>commons-cli</groupId>
-            <artifactId>commons-cli</artifactId>
-            <version>1.2</version>
-            <scope>compile</scope>
-        </dependency>
-	</dependencies>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/adminshell/pom.xml (from rev 2708, branches/7.2.x/adminshell/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/adminshell/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/adminshell/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,69 @@
+<?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">
+	<parent>
+		<artifactId>teiid-parent</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>teiid-adminshell</artifactId>
+	<name>Adminshell</name>
+	<description>Adminshell for Teiid</description>
+	<dependencies>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-common-core</artifactId>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-common-core</artifactId>
+			<type>test-jar</type>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-client</artifactId>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.codehaus.groovy</groupId>
+			<artifactId>groovy-all</artifactId>
+			<version>1.7.2</version>
+		</dependency>
+		<dependency>
+			<groupId>junit</groupId>
+			<artifactId>junit</artifactId>
+			<version>3.8.1</version>
+		</dependency>
+		<dependency>
+			<groupId>junit</groupId>
+			<artifactId>junit</artifactId>
+			<version>4.4</version>
+			<scope>test</scope>
+		</dependency>
+        <dependency>
+            <groupId>jline</groupId>
+            <artifactId>jline</artifactId>
+            <version>0.9.94</version>
+            <scope>compile</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>junit</groupId>
+                    <artifactId>junit</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.fusesource.jansi</groupId>
+            <artifactId>jansi</artifactId>
+            <version>1.2.1</version>
+            <scope>compile</scope>
+        </dependency>
+        <dependency>
+            <groupId>commons-cli</groupId>
+            <artifactId>commons-cli</artifactId>
+            <version>1.2</version>
+            <scope>compile</scope>
+        </dependency>
+	</dependencies>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/api/pom.xml
===================================================================
--- branches/7.2.x/api/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/api/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,34 +0,0 @@
-<?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">
-  <parent>
-    <artifactId>teiid-parent</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>teiid-api</artifactId>
-  <name>Teiid Translator API</name>
-  <description>API for creating Translators and other common extenders in Teiid</description>
-  
-  <dependencies>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <scope>provided</scope>
-    </dependency>
-    
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>
-        
-    <dependency>
-      <groupId>javax.resource</groupId>
-      <artifactId>connector-api</artifactId>
-      <scope>provided</scope>
-    </dependency>
-    
-  </dependencies>
-</project>

Copied: tags/teiid-parent-7.2.0.Final/api/pom.xml (from rev 2708, branches/7.2.x/api/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/api/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/api/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,34 @@
+<?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">
+  <parent>
+    <artifactId>teiid-parent</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>teiid-api</artifactId>
+  <name>Teiid Translator API</name>
+  <description>API for creating Translators and other common extenders in Teiid</description>
+  
+  <dependencies>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+        
+    <dependency>
+      <groupId>javax.resource</groupId>
+      <artifactId>connector-api</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    
+  </dependencies>
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
===================================================================
--- branches/7.2.x/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,221 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-    
-    <!-- Teiid Services -->
-    <bean name="SessionService" class="org.teiid.services.SessionServiceImpl">
-        <property name="VDBRepository"><inject bean="VDBRepository"/></property>
-        <property name="securityHelper"><inject bean="SecurityHelper"/></property>
-        <!-- Comma separated list of domains to be used to login into Teiid using JDBC connection-->
-        <property name="securityDomains">teiid-security</property>
-        <!-- security domain to be used with Admin API (please do not change this, as this should be same as profile service) -->
-        <property name="adminSecurityDomain">jmx-console</property>
-        <!-- Maximum number of sessions allowed by the system (default 5000) -->
-        <property name="sessionMaxLimit">5000</property>
-        <!-- Max allowed time before the session is terminated by the system, 0 indicates unlimited (default 0) -->
-        <property name="sessionExpirationTimeLimit">0</property>
-    </bean>
-    
-    <bean name="BufferService" class="org.teiid.services.BufferServiceImpl">
-        <!-- Use disk for buffer management -->
-        <property name="useDisk">true</property>
-        <!-- Directory location for the buffer files -->
-        <property name="diskDirectory">${jboss.server.temp.dir}/teiid</property>
-        <!-- The max row count of a batch sent internally within the query processor. Should be <= the connectorBatchSize. (default 512) -->
-        <property name="processorBatchSize">512</property>
-        <!-- The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024) -->
-        <property name="connectorBatchSize">1024</property>
-        <!-- 
-            The number of batch columns to allow in memory (default 16384).  
-            This value should be set lower or higher depending on the available memory to Teiid in the VM.  
-            16384 is considered a good default for a dedicated 32-bit VM running Teiid with a 1 gig heap.        
-         -->
-        <property name="maxReserveBatchColumns">16384</property>
-        <!-- 
-            The number of batch columns guaranteed to a processing operation.  Set this value lower if the workload typically
-            processes larger numbers of concurrent queries with large intermediate results from operations such as sorting, 
-            grouping, etc. (default 128)        
-         -->
-        <property name="maxProcessingBatchesColumns">128</property>
-        <!--  Max File size in MB (default 2GB)-->
-        <property name="maxFileSize">2048</property>
-        <!-- Max storage space, in MB, to be used for buffer files (default 50G) -->
-        <property name="maxBufferSpace">51200</property>
-        <!-- Max open buffer files (default 64) -->
-        <property name="maxOpenFiles">64</property> 
-    </bean>
-    
-    <bean name="CacheFactory" class="org.teiid.cache.jboss.ClusterableCacheFactory">
-        <property name="enabled">true</property>
-        <property name="cacheManager">java:TeiidCacheManager</property>
-        <property name="resultsetCacheName">teiid-resultset-cache</property>        
-    </bean>
-    
-    <!-- Configuration for result set caching. 
-    	 There will be 2 caches with these settings.
-    	 One cache holds results that are specific to sessions.
-    	 The other cache holds vdb scoped results and can
-    	 be replicated.
-     -->
-    <bean name="ResultsetCacheConfig" class="org.teiid.cache.CacheConfiguration">
-        <property name="enabled">true</property>
-        <!-- Max Entries allowed for ResultSet Cache (default 1024) -->
-        <property name="maxEntries">1024</property>
-        <!-- Max age in seconds (default 7200 - 2 hours) -->
-        <property name="maxAgeInSeconds">7200</property>
-        <!-- Allowed values are LRU, EXPIRATION.  
-             Setting this value to LRU will cause cache hint TTL values
-             to be ignored. (default EXPIRATION) -->
-        <property name="type">EXPIRATION</property>               
-    </bean>    
-    
-    <bean name="RuntimeEngineDeployer" class="org.teiid.jboss.deployers.RuntimeEngineDeployer">
-        <property name="jndiName">teiid/engine-deployer</property>
-        <property name="profileService"><inject bean="ProfileService"/></property>
-        <property name="jdbcSocketConfiguration"><inject bean="JdbcSocketConfiguration"/></property>
-        <property name="adminSocketConfiguration"><inject bean="AdminSocketConfiguration"/></property>
-        <property name="odbcSocketConfiguration"><inject bean="OdbcSocketConfiguration"/></property>
-        <property name="workManager"><inject bean="WorkManager"/></property>
-        <property name="XATerminator"><inject bean="TransactionManager" property="XATerminator"/></property>
-        <property name="transactionManager"><inject bean="TransactionManager" property="transactionManager"/></property>
-        <property name="sessionService"><inject bean="SessionService"/></property>
-        <property name="bufferService"><inject bean="BufferService"/></property>
-        <property name="securityHelper"><inject bean="SecurityHelper"/></property>
-        <property name="VDBRepository"><inject bean="VDBRepository"/></property>
-        <property name="cacheFactory"><inject bean="CacheFactory"/></property>
-        <property name="resultsetCacheConfig"><inject bean="ResultsetCacheConfig"/></property>
-        
-        <!-- Process pool maximum thread count. (default 64) -->
-        <property name="maxThreads">64</property>
-        <!-- Max active plans (default 20).  Increase this value on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts. -->
-        <property name="maxActivePlans">20</property>
-        <!-- Query processor time slice, in milliseconds. (default 2000) -->
-        <property name="timeSliceInMilli">2000</property>
-        <!-- Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480) -->
-        <property name="maxRowsFetchSize">20480</property>
-        <!-- The max lob chunk size in KB transferred each time when processing blobs, clobs (100KB default) -->
-        <property name="lobChunkSizeInKB">100</property>
-        <!-- The maximum number of query plans that are cached. 
-             This includes both user plans and internal prepared plans.
-             Note: this is a memory based cache. (default 512)  -->
-        <property name="preparedPlanCacheMaxCount">512</property>
-        <!-- Turn on role checking of resources based on the roles defined in VDB (default true) -->
-        <property name="useDataRoles" class="java.lang.Boolean">true</property>
-        <!-- Long running query threshold, after which a alert can be generated by tooling if configured-->
-        <property name="queryThresholdInSecs">600</property>
-		<!-- Maximum rows allowed from a source query. -1 indicates no limit. (default -1)-->
-        <property name="maxSourceRows">-1</property>
-		<!-- Indicates if an exception should be thrown if the specified value for Maximum Source Rows is exceeded; only up to the maximum rows will be consumed. -->        
-        <property name="exceptionOnMaxSourceRows">true</property>
-    </bean>
-
-    <!-- JDBC Socket connection properties (SSL see below) -->
-    <bean name="JdbcSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
-        <property name="enabled">true</property>
-        <property name="bindAddress">${jboss.bind.address}</property>
-        <property name="portNumber">31000</property>
-        <!-- Max number of threads dedicated to initial request processing (default 15) -->
-        <property name="maxSocketThreads">15</property>
-        <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
-        <property name="inputBufferSize">0</property>
-        <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
-        <property name="outputBufferSize">0</property>
-        <property name="SSLConfiguration"><inject bean="JdbcSslConfiguration"/></property>
-    </bean>
-    
-    <bean name="JdbcSslConfiguration" class="org.teiid.transport.SSLConfiguration">
-        <!-- can be one of disabled, login, or enabled 
-             disabled = no transport or message level security will be used
-             login = only the login traffic will be encrypted at a message level
-                     using 128 bit AES with an ephemerial DH key exchange. 
-                     No other config values are needed in this mode
-             enabled = traffic will be secured using this configuration
-        -->
-        <property name="mode">login</property>
-        <property name="keystoreFilename">cert.keystore</property>
-        <property name="keystorePassword">passwd</property>
-        <property name="keystoreType">JKS</property>
-        <property name="sslProtocol">SSLv3</property>
-        <property name="keymanagementAlgorithm">false</property>
-        <property name="truststoreFilename">cert.truststore</property>
-        <property name="truststorePassword">passwd</property>
-        <!--  1-way, 2-way, anonymous -->
-        <property name="authenticationMode">1-way</property>
-    </bean>
-    
-    <!-- Admin Socket connection settings (SSL see below) -->
-    <bean name="AdminSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
-        <property name="enabled">true</property>
-        <property name="bindAddress">${jboss.bind.address}</property>
-        <property name="portNumber">31443</property>
-        <!-- Max number of threads dedicated to Admin and initial request processing (default 4) -->
-        <property name="maxSocketThreads">4</property>
-        <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
-        <property name="inputBufferSize">0</property>
-        <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
-        <property name="outputBufferSize">0</property>
-        <property name="SSLConfiguration"><inject bean="AdminSslConfiguration"/></property>
-    </bean>
-    
-    <bean name="AdminSslConfiguration" class="org.teiid.transport.SSLConfiguration">
-        <!-- can be one of disabled, login, or enabled 
-             disabled = no transport or message level security will be used
-             login = only the login traffic will be encrypted at a message level
-                     using 128 bit AES with an ephemerial DH key exchange. 
-                     No other config values are needed in this mode
-             enabled = traffic will be secured using this configuration
-        -->
-        <property name="mode">enabled</property>
-        <property name="keystoreFilename">cert.keystore</property>
-        <property name="keystorePassword">passwd</property>
-        <property name="keystoreType">JKS</property>
-        <property name="sslProtocol">SSLv3</property>
-        <property name="keymanagementAlgorithm">false</property>
-        <property name="truststoreFilename">cert.truststore</property>
-        <property name="truststorePassword">passwd</property>
-        <!--  1-way, 2-way, anonymous -->
-        <property name="authenticationMode">anonymous</property>
-    </bean>
-    
-    <!-- JDBC Socket connection properties (SSL see below) -->
-    <bean name="OdbcSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
-        <property name="enabled">true</property>
-        <property name="bindAddress">${jboss.bind.address}</property>
-        <property name="portNumber">35432</property>
-        <!-- Max number of threads dedicated to initial request processing (default 15) -->
-        <property name="maxSocketThreads">15</property>
-        <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
-        <property name="inputBufferSize">0</property>
-        <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
-        <property name="outputBufferSize">0</property>
-        <property name="SSLConfiguration"><inject bean="OdbcSslConfiguration"/></property>
-    </bean>
-    
-    <bean name="OdbcSslConfiguration" class="org.teiid.transport.SSLConfiguration">
-        <!-- can be one of disabled or enabled 
-             disabled = no transport or message level security will be used
-             enabled = traffic will be secured using this configuration
-        -->
-        <property name="mode">disabled</property>
-        <property name="keystoreFilename">cert.keystore</property>
-        <property name="keystorePassword">passwd</property>
-        <property name="keystoreType">JKS</property>
-        <property name="sslProtocol">SSLv3</property>
-        <property name="keymanagementAlgorithm">false</property>
-        <property name="truststoreFilename">cert.truststore</property>
-        <property name="truststorePassword">passwd</property>
-        <!--  1-way, 2-way, anonymous -->
-        <property name="authenticationMode">1-way</property>
-    </bean>    
-            
-    <!-- teiid's default security domain, replace this with your own if needs to be any other JAAS domain  -->
-    <application-policy xmlns="urn:jboss:security-beans:1.0" name="teiid-security">
-        <authentication>
-            <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
-                <!-- property files can found under conf/props directory -->
-                <module-option name="usersProperties">props/teiid-security-users.properties</module-option>
-                <module-option name="rolesProperties">props/teiid-security-roles.properties</module-option>
-            </login-module>
-        </authentication>
-    </application-policy>    
-
-</deployment>

Copied: tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml (from rev 2707, branches/7.2.x/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,225 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+    
+    <!-- Teiid Services -->
+    <bean name="SessionService" class="org.teiid.services.SessionServiceImpl">
+        <property name="VDBRepository"><inject bean="VDBRepository"/></property>
+        <property name="securityHelper"><inject bean="SecurityHelper"/></property>
+        <!-- Comma separated list of domains to be used to login into Teiid using JDBC connection-->
+        <property name="securityDomains">teiid-security</property>
+        <!-- security domain to be used with Admin API (please do not change this, as this should be same as profile service) -->
+        <property name="adminSecurityDomain">jmx-console</property>
+        <!-- Maximum number of sessions allowed by the system (default 5000) -->
+        <property name="sessionMaxLimit">5000</property>
+        <!-- Max allowed time before the session is terminated by the system, 0 indicates unlimited (default 0) -->
+        <property name="sessionExpirationTimeLimit">0</property>
+    </bean>
+    
+    <bean name="BufferService" class="org.teiid.services.BufferServiceImpl">
+        <!-- Use disk for buffer management -->
+        <property name="useDisk">true</property>
+        <!-- Directory location for the buffer files -->
+        <property name="diskDirectory">${jboss.server.temp.dir}/teiid</property>
+        <!-- The max row count of a batch sent internally within the query processor. Should be <= the connectorBatchSize. (default 512) -->
+        <property name="processorBatchSize">512</property>
+        <!-- The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024) -->
+        <property name="connectorBatchSize">1024</property>
+        <!-- 
+            The number of batch columns to allow in memory (default 16384).  
+            This value should be set lower or higher depending on the available memory to Teiid in the VM.  
+            16384 is considered a good default for a dedicated 32-bit VM running Teiid with a 1 gig heap.        
+         -->
+        <property name="maxReserveBatchColumns">16384</property>
+        <!-- 
+            The number of batch columns guaranteed to a processing operation.  Set this value lower if the workload typically
+            processes larger numbers of concurrent queries with large intermediate results from operations such as sorting, 
+            grouping, etc. (default 128)        
+         -->
+        <property name="maxProcessingBatchesColumns">128</property>
+        <!--  Max File size in MB (default 2GB)-->
+        <property name="maxFileSize">2048</property>
+        <!-- Max storage space, in MB, to be used for buffer files (default 50G) -->
+        <property name="maxBufferSpace">51200</property>
+        <!-- Max open buffer files (default 64) -->
+        <property name="maxOpenFiles">64</property> 
+    </bean>
+    
+    <bean name="CacheFactory" class="org.teiid.cache.jboss.ClusterableCacheFactory">
+        <property name="enabled">true</property>
+        <property name="cacheManager">java:TeiidCacheManager</property>
+        <property name="resultsetCacheName">teiid-resultset-cache</property>        
+    </bean>
+    
+    <!-- Configuration for result set caching. 
+    	 There will be 2 caches with these settings.
+    	 One cache holds results that are specific to sessions.
+    	 The other cache holds vdb scoped results and can
+    	 be replicated.
+     -->
+    <bean name="ResultsetCacheConfig" class="org.teiid.cache.CacheConfiguration">
+        <property name="name">ResultSetCacheConfig</property>
+        <property name="enabled">true</property>
+        <!-- Max Entries allowed for ResultSet Cache (default 1024) -->
+        <property name="maxEntries">1024</property>
+        <!-- Max age in seconds (default 7200 - 2 hours) -->
+        <property name="maxAgeInSeconds">7200</property>
+        <!-- Allowed values are LRU, EXPIRATION.  
+             Setting this value to LRU will cause cache hint TTL values
+             to be ignored. (default EXPIRATION) -->
+        <property name="type">EXPIRATION</property>               
+    </bean>    
+    
+    <bean name="RuntimeEngineDeployer" class="org.teiid.jboss.deployers.RuntimeEngineDeployer">
+        <property name="jndiName">teiid/engine-deployer</property>
+        <property name="profileService"><inject bean="ProfileService"/></property>
+        <property name="jdbcSocketConfiguration"><inject bean="JdbcSocketConfiguration"/></property>
+        <property name="adminSocketConfiguration"><inject bean="AdminSocketConfiguration"/></property>
+        <property name="odbcSocketConfiguration"><inject bean="OdbcSocketConfiguration"/></property>
+        <property name="workManager"><inject bean="WorkManager"/></property>
+        <property name="XATerminator"><inject bean="TransactionManager" property="XATerminator"/></property>
+        <property name="transactionManager"><inject bean="TransactionManager" property="transactionManager"/></property>
+        <property name="sessionService"><inject bean="SessionService"/></property>
+        <property name="bufferService"><inject bean="BufferService"/></property>
+        <property name="securityHelper"><inject bean="SecurityHelper"/></property>
+        <property name="VDBRepository"><inject bean="VDBRepository"/></property>
+        <property name="cacheFactory"><inject bean="CacheFactory"/></property>
+        <property name="resultsetCacheConfig"><inject bean="ResultsetCacheConfig"/></property>
+        
+        <!-- Process pool maximum thread count. (default 64) -->
+        <property name="maxThreads">64</property>
+        <!-- Max active plans (default 20).  Increase this value on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts. -->
+        <property name="maxActivePlans">20</property>
+        <!-- Query processor time slice, in milliseconds. (default 2000) -->
+        <property name="timeSliceInMilli">2000</property>
+        <!-- Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480) -->
+        <property name="maxRowsFetchSize">20480</property>
+        <!-- The max lob chunk size in KB transferred each time when processing blobs, clobs (100KB default) -->
+        <property name="lobChunkSizeInKB">100</property>
+        <!-- The maximum number of query plans that are cached. 
+             This includes both user plans and internal prepared plans.
+             Note: this is a memory based cache. (default 512)  -->
+        <property name="preparedPlanCacheMaxCount">512</property>
+        <!-- Turn on role checking of resources based on the roles defined in VDB (default true) -->
+        <property name="useDataRoles">true</property>
+        <!-- Long running query threshold, after which a alert can be generated by tooling if configured-->
+        <property name="queryThresholdInSecs">600</property>
+		<!-- Maximum rows allowed from a source query. -1 indicates no limit. (default -1)-->
+        <property name="maxSourceRows">-1</property>
+		<!-- Indicates if an exception should be thrown if the specified value for Maximum Source Rows is exceeded; only up to the maximum rows will be consumed. -->        
+        <property name="exceptionOnMaxSourceRows">true</property>
+    </bean>
+
+    <!-- JDBC Socket connection properties (SSL see below) -->
+    <bean name="JdbcSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
+        <property name="name">JdbcSocketConfiguration</property>
+        <property name="enabled">true</property>
+        <property name="bindAddress">${jboss.bind.address}</property>
+        <property name="portNumber">31000</property>
+        <!-- Max number of threads dedicated to initial request processing (default 15) -->
+        <property name="maxSocketThreads">15</property>
+        <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
+        <property name="inputBufferSize">0</property>
+        <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
+        <property name="outputBufferSize">0</property>
+        <property name="SSLConfiguration"><inject bean="JdbcSslConfiguration"/></property>
+    </bean>
+    
+    <bean name="JdbcSslConfiguration" class="org.teiid.transport.SSLConfiguration">
+        <!-- can be one of disabled, login, or enabled 
+             disabled = no transport or message level security will be used
+             login = only the login traffic will be encrypted at a message level
+                     using 128 bit AES with an ephemerial DH key exchange. 
+                     No other config values are needed in this mode
+             enabled = traffic will be secured using this configuration
+        -->
+        <property name="mode">login</property>
+        <property name="keystoreFilename">cert.keystore</property>
+        <property name="keystorePassword">passwd</property>
+        <property name="keystoreType">JKS</property>
+        <property name="sslProtocol">SSLv3</property>
+        <property name="keymanagementAlgorithm">false</property>
+        <property name="truststoreFilename">cert.truststore</property>
+        <property name="truststorePassword">passwd</property>
+        <!--  1-way, 2-way, anonymous -->
+        <property name="authenticationMode">1-way</property>
+    </bean>
+    
+    <!-- Admin Socket connection settings (SSL see below) -->
+    <bean name="AdminSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
+        <property name="name">AdminSocketConfiguration</property>
+        <property name="enabled">true</property>
+        <property name="bindAddress">${jboss.bind.address}</property>
+        <property name="portNumber">31443</property>
+        <!-- Max number of threads dedicated to Admin and initial request processing (default 4) -->
+        <property name="maxSocketThreads">4</property>
+        <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
+        <property name="inputBufferSize">0</property>
+        <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
+        <property name="outputBufferSize">0</property>
+        <property name="SSLConfiguration"><inject bean="AdminSslConfiguration"/></property>
+    </bean>
+    
+    <bean name="AdminSslConfiguration" class="org.teiid.transport.SSLConfiguration">
+        <!-- can be one of disabled, login, or enabled 
+             disabled = no transport or message level security will be used
+             login = only the login traffic will be encrypted at a message level
+                     using 128 bit AES with an ephemerial DH key exchange. 
+                     No other config values are needed in this mode
+             enabled = traffic will be secured using this configuration
+        -->
+        <property name="mode">enabled</property>
+        <property name="keystoreFilename">cert.keystore</property>
+        <property name="keystorePassword">passwd</property>
+        <property name="keystoreType">JKS</property>
+        <property name="sslProtocol">SSLv3</property>
+        <property name="keymanagementAlgorithm">false</property>
+        <property name="truststoreFilename">cert.truststore</property>
+        <property name="truststorePassword">passwd</property>
+        <!--  1-way, 2-way, anonymous -->
+        <property name="authenticationMode">anonymous</property>
+    </bean>
+    
+    <!-- JDBC Socket connection properties (SSL see below) -->
+    <bean name="OdbcSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
+        <property name="name">OdbcSocketConfiguration</property>
+        <property name="enabled">true</property>
+        <property name="bindAddress">${jboss.bind.address}</property>
+        <property name="portNumber">35432</property>
+        <!-- Max number of threads dedicated to initial request processing (default 15) -->
+        <property name="maxSocketThreads">15</property>
+        <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
+        <property name="inputBufferSize">0</property>
+        <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
+        <property name="outputBufferSize">0</property>
+        <property name="SSLConfiguration"><inject bean="OdbcSslConfiguration"/></property>
+    </bean>
+    
+    <bean name="OdbcSslConfiguration" class="org.teiid.transport.SSLConfiguration">
+        <!-- can be one of disabled or enabled 
+             disabled = no transport or message level security will be used
+             enabled = traffic will be secured using this configuration
+        -->
+        <property name="mode">disabled</property>
+        <property name="keystoreFilename">cert.keystore</property>
+        <property name="keystorePassword">passwd</property>
+        <property name="keystoreType">JKS</property>
+        <property name="sslProtocol">SSLv3</property>
+        <property name="keymanagementAlgorithm">false</property>
+        <property name="truststoreFilename">cert.truststore</property>
+        <property name="truststorePassword">passwd</property>
+        <!--  1-way, 2-way, anonymous -->
+        <property name="authenticationMode">1-way</property>
+    </bean>    
+            
+    <!-- teiid's default security domain, replace this with your own if needs to be any other JAAS domain  -->
+    <application-policy xmlns="urn:jboss:security-beans:1.0" name="teiid-security">
+        <authentication>
+            <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
+                <!-- property files can found under conf/props directory -->
+                <module-option name="usersProperties">props/teiid-security-users.properties</module-option>
+                <module-option name="rolesProperties">props/teiid-security-roles.properties</module-option>
+            </login-module>
+        </authentication>
+    </application-policy>    
+
+</deployment>

Deleted: tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/teiid-releasenotes.html
===================================================================
--- branches/7.2.x/build/kits/jboss-container/teiid-releasenotes.html	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/teiid-releasenotes.html	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,209 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<HTML>
-<HEAD>
-	<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">
-	<TITLE>Teiid ${project.version} Release Notes</TITLE>
-	<META NAME="CHANGEDBY" CONTENT="Steve Hawkins">
-	</STYLE>
-</HEAD>
-<BODY LANG="en-US" DIR="LTR">
-<P><A HREF="http://www.teiid.org/"><IMG SRC="https://www.jboss.org/dms/teiid/images/teiid_banner.png" NAME="graphics1" ALT="Teiid" ALIGN=BOTTOM WIDTH=800></A>
-
-<H1>Teiid ${project.version} Release Notes</H1>
-<P>Teiid ${project.version} adds performance and integration features. 
-
-<H2>Overview</H2>
-<UL>
-	<LI><A HREF="#Highlights">Highlights</A>
-	<LI><A HREF="#Compatibility">Compatibility Issues</A> 
-	<LI><A HREF="#Configuration">Configuration Issues</A> 
-	<LI><A HREF="#Other">Other Issues</A> 
-	<LI><A HREF="#LibraryUpdates">Thirdparty Library Updates</A> 
-	<LI><A HREF="#Details">Detailed Release Notes</A> 
-	<LI><A HREF="#Documentation">Additional Docs and Help</A> 
-	<LI><A HREF="#Licenses">Licenses</A> 
-	<LI><A HREF="#About">About JBoss</A> 
-</UL>
-<H2><A NAME="Highlights"></A>Highlights</H2>
-<UL>
-	<LI><B>SQL Support</B>
-	    <UL>
-	       <LI><B>Non-Recursive Common Table Expressions</B> - The WITH clause (and associated pushdown) for non-recursive queries is now supported.
-	       <LI><B>Explicit Table Syntax</B> - TABLE x can now be used as a shortcut for SELECT * FROM x
-	    </UL>
-	<LI><B>JSON Support</B> - JSON, which could be obtained through the ws-translator using http calls or other methods, can be converted to XML using the system function jsonToXml.  XMLTABLE and other integration logic can then be used on the JSON results.
-    <LI><B>Transaction Statements</B> - JDBC/ODBC now accepts START TRANSACTION, COMMIT, and ROLLBACK statements to control local transactions.
-	<LI><B>Procedure Result Caching</B> - virtual procedure definitions may use a cache hint to cache results in the result set cache.
-	<LI><B>Improved Plan Caching</B> - plans used by internal materialization and stored procedure plans will be automatically cached in the prepared plan cache.  Improvements were also made to reduce the memory footprint of the plans.
-    <LI><B>Refined Load Balancing and Fail Over</B> - clients can use use the statement "SET NEWINSTANCE TRUE" to allow their connection to select a new server instance.  See the Client Developer's Guide for more information. 
-    <LI><B>Simplified Role Usage</B> - a role can now be assigned to any authenticated user via the any-authenticated attribute on the data-role element.
-    <LI><B>Materialized View Performance</B> - materialized view tables will now automatically create and use non-unique secondary indexes for unique constraints and indexes defined on the view. 
-    <LI><B>Binary Web Service Calls</B> - the ws translator now provides an invokeHttp procedure to return the blob contents and string content type of an http/https call.
-    <LI><B>Improved clustering support</B> - see the Admin Guide chapter on clustering.
-    <LI><B>IPv6 support</B> - Teiid can started using IPv6 bind address and can be used with JDBC connection.
-    <LI><B>SESSION_ID</B> - A new system function "SESSION_ID" is added to the system function library.
-    <LI><B>Assignment Syntax Improvements<B> - Teiid's procedure syntax for assignments was clarified so that the assignment value must be a proper expression.  INSERT/UPDATE/DELETE update counts must be obtained from VARIABLES.ROWCOUNT, scalar values must be obtained via a scalar subquery. The parser will continue to accept the old syntax and convert the query into the proper form.
-    <LI><B>TEXTAGG</B> - SQL support for Text aggregation. Using this function expression values can be aggregated into a CSV BLOB with configurable delimiter, header, and encoding.  The result can be optionally saved to a text file.   
-</UL>
-
-<h2><a name="Compatibility">Compatibility Issues</a></h2>
-<ul>
-  <li>Support for named parameter syntax using param=value has been deprecated, since it is ambiguous with a comparison predicate boolean value expression.  param<b>=></b>value should be used instead.  
-</ul>
-<h4>from 7.1</h4>
-<ul>
-  <li>Subqueries are no longer allowed to be SELECT INTO.
-  <li>INSERT/UPDATE/DELETE cannot be used to create implicit return cursors in non-update virtual procedures.  You can instead use "UPDATE ...; SELECT VARIABLES.ROWCOUNT;".  
-  <li>The SYSADMIN schema was created to hold procedures and tables that should not be generally accessible.  SYS and pg_catalog are now always accessible - permissions do not apply to these schemas.  The SYS.getBinaryVDBResource, SYS.getCharacterVDBResource, and SYS.getVDBResourcePaths have been replaced with the
- SYSADMIN.VDBResources table.  The Matviews table and the refreshMatView/refreshMatViewRow procedures were also moved into SYSADMIN.
-  <li>Overwriting an existing VDB will cause old connections to be terminated.  Production systems should rely on VDB versioning.
-  <li>The jdbc:metamatrix JDBC URL prefix is no longer accepted.  Use jdbc:teiid instead.
-  <li>Model visibility no longer restricts access to tables and procedures.  Setting visible to false will only hide entries from system tables.  Data roles should be used to restrict data access.
-  <li>Admin API "getWorkManagerStats" methods renamed to "getWorkerPoolStats". Also, "setRuntimeProperty" and "getProcesses" methods were removed.
-  <li>By default the "ENV" system function is now turned off. To enable it, edit the teiid-jboss-beans.xml configuration file.
-  <li>The use of VARIABLES.ROWCOUNT is now reserved.
-  <li>Exec statements of the form "var = EXEC foo()" are only valid if the procedure foo has a return parameter.
-</ul>
-<h4>from 7.0</h4>
-<ul>
-  <li>The term data policy was replaced with data role.  The AdminAPI methods for adding role mappings have changed from addRoleToDataPolicy and removeRoleFromDataPolicy to addDataRoleMapping and removeDataRoleMapping respectively.
-</ul>
-<h4>from 6.2</h4>
-<ul>
-  <li>The connector API has changed substantially.  Custom connectors need to be retargeted to the new Translator API.  See <a href="https://jira.jboss.org/browse/TEIID-1003">TEIID-1003</a> and the <a href="teiid-docs/teiid_developers_guide.pdf">Developer's Guide</a> for more information.
-  <li>Connector bindings are no longer valid.  Use the Designer Tooling or see the AdminShell download for a migration utility.
-  <li>Calling out to web services and xml processing has been dramatically simplified and improved, but is a breaking change from prior releases.
-  XML/Relational processing has been replaced by XMLTABLE, retrieving XML from file has been replaced by the File Translator/Resource Adapter, and
-  web service calls have been replaced by the WS Translator/Resource Adapter.  See <a href="https://jira.jboss.org/browse/TEIID-1118">TEIID-1118</a>, <a href="https://jira.jboss.org/browse/TEIID-1114">TEIID-1114</a>, and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
-  <li>The direct usage of XQuery has been replaced with the XMLQuery function.
-  <li>The text connector file processing has been replaced with the TEXTTABLE function.  See <a href="https://jira.jboss.org/browse/TEIID-1102">TEIID-1102</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information
-  <li>Double quoted values are now parsed as identifiers by default.  See <a href="https://jira.jboss.org/browse/TEIID-145">TEIID-145</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
-  <li>The system information schema has changed from System to SYS.  The tables and table structures have also changed.  See <a href="https://jira.jboss.org/browse/TEIID-871">TEIID-871</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
-  <li>Client control over query plans has changed.  OPTION PLANONLY, DEBUG, and SHOWPLAN are no longer allowed.  This behavior should not be controlled by the SET statement, SET SHOWPLAN (ON|OFF|DEBUG) and SET NOEXEC (ON|OFF).  Usage of the client PlanNode class will also need to be updated.   
-  <li>Teiid specific JDBC client interfaces and methods have changed.  In general these custom features have mostly been moved to other more standard locations or been removed. See <a href="https://jira.jboss.org/browse/TEIID-1020">TEIID-1020</a> and the <a href="teiid-docs/teiid_client_developers_guide.pdf">Client Developers</a> guide for more information.  
-  <li>Teiid's reserved words have changed.  Many of the Teiid specific reserved words have become non-reserved words.  All of SQL Foundation and SQL/MED 2003, and SQL/XML from SQL 2006 reserved words have been added as reserved words.  It is generally required to double quote all reserved words.  It is advisable to double quote all non-reserved words as well.  The use of the INPUT qualifier for procedure inputs has been deprecated in favor of INPUTS.  The use of the USING qualifier for dynamic SQL inputs has been deprecated in favor of DVARS.
-  <li>The AdminApi has been redesigned for use with the new Translator/JCA split and for deployment in JBoss AS.
-  <li>The AdminShell is based on Groovy.  Most BeanShell syntax is also valid in Groovy, but there are extensive changes in the AdminAPI that may necessitate rewriting scripts.
-  <li>OPTION NO CACHE &lt;table list&gt; will now only by-pass cache for the given tables at their immediate view layer.  Previously all caches would have transitively been skipped.  See <a href="https://jira.jboss.org/browse/TEIID-900">TEIID-900</a> for more information.
-  <li>Nan and +-Infinity are no longer allowed as numerical results by default.  This may be changed via the system property org.teiid.allowNanInfinity.
-  <li>The scale of BigDecimal values is now adjusted to allow for more intuitive results.  Conversion from floating numeric types will preserve the approximate scale and division results will allow for additional scale.  See <a href="https://jira.jboss.org/browse/TEIID-159">TEIID-159</a> for more information.
-  <li>The 7.0 client is not compatible with 6.x or vice versa.  It is expected that 7.0 clients will be compatible with 7.x releases for standard JDBC operations.
-</ul>
-
-<h2><a name="Configuration">Configuration Issues</a></h2>
-
-See the <a href="teiid-docs/teiid_admin_guide.pdf">Admin Guide</a> for more on configuration and installation.
-
-<h4>from 7.1</h4>
-<ul>
-    <li>Teiid clients now allow the usage of anonymous SSL by default.  
-    This changes allows the admin port (default 31443) to use anonymous SSL by default, rather than just securing login traffic.  
-    Admin clients should therefore use the mms protocol instead of mm.  This will encrypt all admin traffic and ensure that any passwords in configuration files will
-    be encrypted in transit.  See the Admin Guide to upgrade from anonymous SSL to 1-way or 2-way authentication.
-    The config properties sslEnabled and clientEncryptionEnabled for SSLConfiguration beans have been combined to a single property mode, that can have the values disabled|login|enabled.
-	<li>Apache CXF is now expected to be used as the web services stack provider through JBossWS-CXF.  See the Admin Guide for instructions on 
-	installing CXF for use with Teiid's Salesforce and web service connectors.  The WS Resource Adapter's -ds.xml files should no longer use 
-	WSSecurityConfigURL and WSSecurityConfigName, rather they should be ConfigFile and ConfigName respectively.  The property values should no longer
-	refer to jboss-wsse-client.xml, but instead they should reference a CXF Spring configuration file and particular port configuration.  See the Admin Guide
-	for more on using CXF configuration files. 
-	<li>The default for data role checking is now "true".  However only VDBs with data roles will have roles enforced.
-	<li>The default prepared plan cache size was increased to 512, since it is targeted by internal plans as well.
-</ul>
-
-<h4>from 7.0</h4>
-<ul>
-    <li>The property to enable data roles in teiid-jboss-beans.xml has changed from useEntitlements to useDataRoles.
-	<li>Rar file names no longer contain version numbers.  -ds.xml files should be updated from connector-XXX-version.rar to teiid-connector-XXX.rar
-	<li>Code table relate configuration properties have been removed.  Code tables are now implemented as materialized views.
-</ul>
-
-<h4>from 6.2</h4>
-<ul>
-  <li>A JBoss AS instance is now required.  Embedded mode is also currently not supported.</li>
-  <li>Engine configuration is now handled through the admin console or deploy/teiid/teiid-jboss-beans.xml 
-  <li>Logging is now done through the container's log4j instance.  Any Teiid specific logging changes, see the conf/jboss-teiid-log4j.xml, need to be incorporated into the master jboss-log4j.xml.
-</ul>
-
-<h2><a name="Other">Other Issues</a></h2>
-<ul>
-	<li>For compatibility with the 7.0 release if a stored procedure parameter list begins with identifier=, then it will be parsed as a named parameter invocation even if the intent was to use a comparison predicate 
-	as the first parameter value.  The workaround is to use nesting parens, e.g. call proc((identifier=value), ...), which clarifies that this is positional value.  This workaround will not be needed in later releases.  
-</ul>
-<h4>from 7.0</h4>
-<ul>
-  <li>Fixed xsd type handling for SQL/XML and XML document models.  xsd:date, xsd:dateTime, and xsd:time types will now all be displayed using the GMT timezone (Z).  SQL types, such as timestamp, used for an XMLTABLE column will now expect their values to be in the form of the corresponding xsd type.
-</ul>
-<h4>From 6.2</h4>
-<ul>
-  <li>Start time is now significantly longer due to the container deployment.  However many operations can be performed on configruation files that will trigger a redeployment without the need for a restart.
-  <li>Inversion of parse, format, and convert system functions is not used if it can be narrowing.  In situations where a predicate has the form: parseTime(column, 'format') = {t 'time value'} may lead to reduced performance, since
-      the parseTime function cannot be pushed down.  This should be addressed in future releases.   
-</ul>
-
-<h2><a name="LibraryUpdates">Thirdparty Library Updates</a></h2>
-
-The following components have been updated:
-<h4>From 7.1</h4>
-<ul>
-    <li>json-simple 1.1 was added.
-	<li>Netty was upgraded to 3.2.1	
-</ul>
-<h4>From 7.0</h4>
-<ul>
-	<li>Direct integration of JBossCache jars was removed.
-	<li>Netty was upgraded to 3.2.0	
-	<li>JDOM was removed.
-</ul>
-<h4>From 6.2</h4>
-<ul>
-	<li>Netty was upgraded to 3.1.5
-	<li>Saxon was upgraded to 9.1.0.8
-    <li>A 5.1 container's version of Arjuna is newer than what was previously included in Teiid 6.x.
-	<li>Various other dependencies have been removed as they are no longer needed or now provided by the container.
-</ul> 
-
-<h2><a name="Details">Detailed Release Notes</a></h2>
-        Detailed Release Notes - Teiid - Version ${project.version}
-    
-<h2><a name="Documentation">Documentation and Help</a></h2>
-
-The <a href="http://www.jboss.org/teiid/">Teiid community project</a> is hosted on jboss.org.
-Documentation and help may be obtained from the local distribution under <a href="teiid-docs">teiid-docs</a> or the following locations.
-<ul>
-
-<li><a href="http://www.jboss.org/teiid/docs">Online Documentation</a></li>
-<li><a href="https://community.jboss.org/wiki/TheTeiidProject">Wiki</a></li>
-<li><a href="http://jira.jboss.org/jira/browse/TEIID">JIRA</a></li>
-<li><a href="http://community.jboss.org/en/teiid?view=discussions">Forums</a></li>
-</ul>
-
-
-<h2><a name="Licenses">Licenses</a></h2>
-
-<p>Teiid is licensed under the <a href="LICENSE-lgpl-2.1.txt">LGPL</a>. The
-license texts for Teiid and the thirdparty components it uses may be found in the teiid-docs/licenses
-directory of the distribution. <a href="teiid-docs/licenses">Browse
-Licenses</a>
-
-</p>
-
-<h2><a name="About">About JBoss, a
-division of Red Hat</a></h2>
-
-<p>JBoss, a division of <a href="http://www.redhat.com/jboss/">Red
-Hat</a>, is in the business of
-providing
-superior technical support to our customers. Our goal is to make
-Professional Open Source&trade; the <b>SAFE
-CHOICE</b>
-for you. We accomplish this by backing up our open source Java products
-with technical support services that are delivered by the core
-developers themselves. We can help you to train your staff and provide
-you with support at every stage of the application lifecycle - from
-development and integration through deployment and maintenance. Visit
-the <a href="http://www.jboss.com/services/index">JBoss
-Services</a> page for more
-information.</p>
-
-</BODY>
-</HTML>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/teiid-releasenotes.html (from rev 2707, branches/7.2.x/build/kits/jboss-container/teiid-releasenotes.html)
===================================================================
--- tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/teiid-releasenotes.html	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/build/kits/jboss-container/teiid-releasenotes.html	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,210 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML>
+<HEAD>
+	<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">
+	<TITLE>Teiid ${project.version} Release Notes</TITLE>
+	<META NAME="CHANGEDBY" CONTENT="Steve Hawkins">
+	</STYLE>
+</HEAD>
+<BODY LANG="en-US" DIR="LTR">
+<P><A HREF="http://www.teiid.org/"><IMG SRC="https://www.jboss.org/dms/teiid/images/teiid_banner.png" NAME="graphics1" ALT="Teiid" ALIGN=BOTTOM WIDTH=800></A>
+
+<H1>Teiid ${project.version} Release Notes</H1>
+<P>Teiid ${project.version} adds performance and integration features. 
+
+<H2>Overview</H2>
+<UL>
+	<LI><A HREF="#Highlights">Highlights</A>
+	<LI><A HREF="#Compatibility">Compatibility Issues</A> 
+	<LI><A HREF="#Configuration">Configuration Issues</A> 
+	<LI><A HREF="#Other">Other Issues</A> 
+	<LI><A HREF="#LibraryUpdates">Thirdparty Library Updates</A> 
+	<LI><A HREF="#Details">Detailed Release Notes</A> 
+	<LI><A HREF="#Documentation">Additional Docs and Help</A> 
+	<LI><A HREF="#Licenses">Licenses</A> 
+	<LI><A HREF="#About">About JBoss</A> 
+</UL>
+<H2><A NAME="Highlights"></A>Highlights</H2>
+<UL>
+	<LI><B>SQL Support</B>
+	    <UL>
+	       <LI><B>Non-Recursive Common Table Expressions</B> - The WITH clause (and associated pushdown) for non-recursive queries is now supported.
+	       <LI><B>Explicit Table Syntax</B> - TABLE x can now be used as a shortcut for SELECT * FROM x
+	    </UL>
+	<LI><B>JSON Support</B> - JSON, which could be obtained through the ws-translator using http calls or other methods, can be converted to XML using the system function jsonToXml.  XMLTABLE and other integration logic can then be used on the JSON results.
+    <LI><B>Transaction Statements</B> - JDBC/ODBC now accepts START TRANSACTION, COMMIT, and ROLLBACK statements to control local transactions.
+	<LI><B>Procedure Result Caching</B> - virtual procedure definitions may use a cache hint to cache results in the result set cache.
+	<LI><B>Improved Plan Caching</B> - plans used by internal materialization and stored procedure plans will be automatically cached in the prepared plan cache.  Improvements were also made to reduce the memory footprint of the plans.
+    <LI><B>Refined Load Balancing and Fail Over</B> - clients can use use the statement "SET NEWINSTANCE TRUE" to allow their connection to select a new server instance.  See the Client Developer's Guide for more information. 
+    <LI><B>Simplified Role Usage</B> - a role can now be assigned to any authenticated user via the any-authenticated attribute on the data-role element.
+    <LI><B>Materialized View Performance</B> - materialized view tables will now automatically create and use non-unique secondary indexes for unique constraints and indexes defined on the view. 
+    <LI><B>Binary Web Service Calls</B> - the ws translator now provides an invokeHttp procedure to return the blob contents and string content type of an http/https call.
+    <LI><B>Improved clustering support</B> - see the Admin Guide chapter on clustering.
+    <LI><B>IPv6 support</B> - Teiid can started using IPv6 bind address and can be used with JDBC connection.
+    <LI><B>SESSION_ID</B> - A new system function "SESSION_ID" is added to the system function library.
+    <LI><B>Assignment Syntax Improvements</B> - Teiid's procedure syntax for assignments was clarified so that the assignment value must be a proper expression.  INSERT/UPDATE/DELETE update counts must be obtained from VARIABLES.ROWCOUNT, scalar values must be obtained via a scalar subquery. The parser will continue to accept the old syntax and convert the query into the proper form.
+    <LI><B>TEXTAGG</B> - SQL support for Text aggregation. Using this function expression values can be aggregated into a CSV BLOB with configurable delimiter, header, and encoding.  The result can be optionally saved to a text file.   
+</UL>
+
+<h2><a name="Compatibility">Compatibility Issues</a></h2>
+<ul>
+  <li>TRANSLATE CRITERIA has been deprecated.  An alternative approach to update procedures will be introduced in a subsequent version.
+  <li>Support for named parameter syntax using param=value has been deprecated, since it is ambiguous with a comparison predicate boolean value expression.  param<b>=></b>value should be used instead.  
+</ul>
+<h4>from 7.1</h4>
+<ul>
+  <li>Subqueries are no longer allowed to be SELECT INTO.
+  <li>INSERT/UPDATE/DELETE cannot be used to create implicit return cursors in non-update virtual procedures.  You can instead use "UPDATE ...; SELECT VARIABLES.ROWCOUNT;".  
+  <li>The SYSADMIN schema was created to hold procedures and tables that should not be generally accessible.  SYS and pg_catalog are now always accessible - permissions do not apply to these schemas.  The SYS.getBinaryVDBResource, SYS.getCharacterVDBResource, and SYS.getVDBResourcePaths have been replaced with the
+ SYSADMIN.VDBResources table.  The Matviews table and the refreshMatView/refreshMatViewRow procedures were also moved into SYSADMIN.
+  <li>Overwriting an existing VDB will cause old connections to be terminated.  Production systems should rely on VDB versioning.
+  <li>The jdbc:metamatrix JDBC URL prefix is no longer accepted.  Use jdbc:teiid instead.
+  <li>Model visibility no longer restricts access to tables and procedures.  Setting visible to false will only hide entries from system tables.  Data roles should be used to restrict data access.
+  <li>Admin API "getWorkManagerStats" methods renamed to "getWorkerPoolStats". Also, "setRuntimeProperty" and "getProcesses" methods were removed.
+  <li>By default the "ENV" system function is now turned off. To enable it, edit the teiid-jboss-beans.xml configuration file.
+  <li>The use of VARIABLES.ROWCOUNT is now reserved.
+  <li>Exec statements of the form "var = EXEC foo()" are only valid if the procedure foo has a return parameter.
+</ul>
+<h4>from 7.0</h4>
+<ul>
+  <li>The term data policy was replaced with data role.  The AdminAPI methods for adding role mappings have changed from addRoleToDataPolicy and removeRoleFromDataPolicy to addDataRoleMapping and removeDataRoleMapping respectively.
+</ul>
+<h4>from 6.2</h4>
+<ul>
+  <li>The connector API has changed substantially.  Custom connectors need to be retargeted to the new Translator API.  See <a href="https://jira.jboss.org/browse/TEIID-1003">TEIID-1003</a> and the <a href="teiid-docs/teiid_developers_guide.pdf">Developer's Guide</a> for more information.
+  <li>Connector bindings are no longer valid.  Use the Designer Tooling or see the AdminShell download for a migration utility.
+  <li>Calling out to web services and xml processing has been dramatically simplified and improved, but is a breaking change from prior releases.
+  XML/Relational processing has been replaced by XMLTABLE, retrieving XML from file has been replaced by the File Translator/Resource Adapter, and
+  web service calls have been replaced by the WS Translator/Resource Adapter.  See <a href="https://jira.jboss.org/browse/TEIID-1118">TEIID-1118</a>, <a href="https://jira.jboss.org/browse/TEIID-1114">TEIID-1114</a>, and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
+  <li>The direct usage of XQuery has been replaced with the XMLQuery function.
+  <li>The text connector file processing has been replaced with the TEXTTABLE function.  See <a href="https://jira.jboss.org/browse/TEIID-1102">TEIID-1102</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information
+  <li>Double quoted values are now parsed as identifiers by default.  See <a href="https://jira.jboss.org/browse/TEIID-145">TEIID-145</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
+  <li>The system information schema has changed from System to SYS.  The tables and table structures have also changed.  See <a href="https://jira.jboss.org/browse/TEIID-871">TEIID-871</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
+  <li>Client control over query plans has changed.  OPTION PLANONLY, DEBUG, and SHOWPLAN are no longer allowed.  This behavior should not be controlled by the SET statement, SET SHOWPLAN (ON|OFF|DEBUG) and SET NOEXEC (ON|OFF).  Usage of the client PlanNode class will also need to be updated.   
+  <li>Teiid specific JDBC client interfaces and methods have changed.  In general these custom features have mostly been moved to other more standard locations or been removed. See <a href="https://jira.jboss.org/browse/TEIID-1020">TEIID-1020</a> and the <a href="teiid-docs/teiid_client_developers_guide.pdf">Client Developers</a> guide for more information.  
+  <li>Teiid's reserved words have changed.  Many of the Teiid specific reserved words have become non-reserved words.  All of SQL Foundation and SQL/MED 2003, and SQL/XML from SQL 2006 reserved words have been added as reserved words.  It is generally required to double quote all reserved words.  It is advisable to double quote all non-reserved words as well.  The use of the INPUT qualifier for procedure inputs has been deprecated in favor of INPUTS.  The use of the USING qualifier for dynamic SQL inputs has been deprecated in favor of DVARS.
+  <li>The AdminApi has been redesigned for use with the new Translator/JCA split and for deployment in JBoss AS.
+  <li>The AdminShell is based on Groovy.  Most BeanShell syntax is also valid in Groovy, but there are extensive changes in the AdminAPI that may necessitate rewriting scripts.
+  <li>OPTION NO CACHE &lt;table list&gt; will now only by-pass cache for the given tables at their immediate view layer.  Previously all caches would have transitively been skipped.  See <a href="https://jira.jboss.org/browse/TEIID-900">TEIID-900</a> for more information.
+  <li>Nan and +-Infinity are no longer allowed as numerical results by default.  This may be changed via the system property org.teiid.allowNanInfinity.
+  <li>The scale of BigDecimal values is now adjusted to allow for more intuitive results.  Conversion from floating numeric types will preserve the approximate scale and division results will allow for additional scale.  See <a href="https://jira.jboss.org/browse/TEIID-159">TEIID-159</a> for more information.
+  <li>The 7.0 client is not compatible with 6.x or vice versa.  It is expected that 7.0 clients will be compatible with 7.x releases for standard JDBC operations.
+</ul>
+
+<h2><a name="Configuration">Configuration Issues</a></h2>
+
+See the <a href="teiid-docs/teiid_admin_guide.pdf">Admin Guide</a> for more on configuration and installation.
+
+<h4>from 7.1</h4>
+<ul>
+    <li>Teiid clients now allow the usage of anonymous SSL by default.  
+    This changes allows the admin port (default 31443) to use anonymous SSL by default, rather than just securing login traffic.  
+    Admin clients should therefore use the mms protocol instead of mm.  This will encrypt all admin traffic and ensure that any passwords in configuration files will
+    be encrypted in transit.  See the Admin Guide to upgrade from anonymous SSL to 1-way or 2-way authentication.
+    The config properties sslEnabled and clientEncryptionEnabled for SSLConfiguration beans have been combined to a single property mode, that can have the values disabled|login|enabled.
+	<li>Apache CXF is now expected to be used as the web services stack provider through JBossWS-CXF.  See the Admin Guide for instructions on 
+	installing CXF for use with Teiid's Salesforce and web service connectors.  The WS Resource Adapter's -ds.xml files should no longer use 
+	WSSecurityConfigURL and WSSecurityConfigName, rather they should be ConfigFile and ConfigName respectively.  The property values should no longer
+	refer to jboss-wsse-client.xml, but instead they should reference a CXF Spring configuration file and particular port configuration.  See the Admin Guide
+	for more on using CXF configuration files. 
+	<li>The default for data role checking is now "true".  However only VDBs with data roles will have roles enforced.
+	<li>The default prepared plan cache size was increased to 512, since it is targeted by internal plans as well.
+</ul>
+
+<h4>from 7.0</h4>
+<ul>
+    <li>The property to enable data roles in teiid-jboss-beans.xml has changed from useEntitlements to useDataRoles.
+	<li>Rar file names no longer contain version numbers.  -ds.xml files should be updated from connector-XXX-version.rar to teiid-connector-XXX.rar
+	<li>Code table relate configuration properties have been removed.  Code tables are now implemented as materialized views.
+</ul>
+
+<h4>from 6.2</h4>
+<ul>
+  <li>A JBoss AS instance is now required.  Embedded mode is also currently not supported.</li>
+  <li>Engine configuration is now handled through the admin console or deploy/teiid/teiid-jboss-beans.xml 
+  <li>Logging is now done through the container's log4j instance.  Any Teiid specific logging changes, see the conf/jboss-teiid-log4j.xml, need to be incorporated into the master jboss-log4j.xml.
+</ul>
+
+<h2><a name="Other">Other Issues</a></h2>
+<ul>
+	<li>For compatibility with the 7.0 release if a stored procedure parameter list begins with identifier=, then it will be parsed as a named parameter invocation even if the intent was to use a comparison predicate 
+	as the first parameter value.  The workaround is to use nesting parens, e.g. call proc((identifier=value), ...), which clarifies that this is positional value.  This workaround will not be needed in later releases.  
+</ul>
+<h4>from 7.0</h4>
+<ul>
+  <li>Fixed xsd type handling for SQL/XML and XML document models.  xsd:date, xsd:dateTime, and xsd:time types will now all be displayed using the GMT timezone (Z).  SQL types, such as timestamp, used for an XMLTABLE column will now expect their values to be in the form of the corresponding xsd type.
+</ul>
+<h4>From 6.2</h4>
+<ul>
+  <li>Start time is now significantly longer due to the container deployment.  However many operations can be performed on configruation files that will trigger a redeployment without the need for a restart.
+  <li>Inversion of parse, format, and convert system functions is not used if it can be narrowing.  In situations where a predicate has the form: parseTime(column, 'format') = {t 'time value'} may lead to reduced performance, since
+      the parseTime function cannot be pushed down.  This should be addressed in future releases.   
+</ul>
+
+<h2><a name="LibraryUpdates">Thirdparty Library Updates</a></h2>
+
+The following components have been updated:
+<h4>From 7.1</h4>
+<ul>
+    <li>json-simple 1.1 was added.
+	<li>Netty was upgraded to 3.2.1	
+</ul>
+<h4>From 7.0</h4>
+<ul>
+	<li>Direct integration of JBossCache jars was removed.
+	<li>Netty was upgraded to 3.2.0	
+	<li>JDOM was removed.
+</ul>
+<h4>From 6.2</h4>
+<ul>
+	<li>Netty was upgraded to 3.1.5
+	<li>Saxon was upgraded to 9.1.0.8
+    <li>A 5.1 container's version of Arjuna is newer than what was previously included in Teiid 6.x.
+	<li>Various other dependencies have been removed as they are no longer needed or now provided by the container.
+</ul> 
+
+<h2><a name="Details">Detailed Release Notes</a></h2>
+        Detailed Release Notes - Teiid - Version ${project.version}
+    
+<h2><a name="Documentation">Documentation and Help</a></h2>
+
+The <a href="http://www.jboss.org/teiid/">Teiid community project</a> is hosted on jboss.org.
+Documentation and help may be obtained from the local distribution under <a href="teiid-docs">teiid-docs</a> or the following locations.
+<ul>
+
+<li><a href="http://www.jboss.org/teiid/docs">Online Documentation</a></li>
+<li><a href="https://community.jboss.org/wiki/TheTeiidProject">Wiki</a></li>
+<li><a href="http://jira.jboss.org/jira/browse/TEIID">JIRA</a></li>
+<li><a href="http://community.jboss.org/en/teiid?view=discussions">Forums</a></li>
+</ul>
+
+
+<h2><a name="Licenses">Licenses</a></h2>
+
+<p>Teiid is licensed under the <a href="LICENSE-lgpl-2.1.txt">LGPL</a>. The
+license texts for Teiid and the thirdparty components it uses may be found in the teiid-docs/licenses
+directory of the distribution. <a href="teiid-docs/licenses">Browse
+Licenses</a>
+
+</p>
+
+<h2><a name="About">About JBoss, a
+division of Red Hat</a></h2>
+
+<p>JBoss, a division of <a href="http://www.redhat.com/jboss/">Red
+Hat</a>, is in the business of
+providing
+superior technical support to our customers. Our goal is to make
+Professional Open Source&trade; the <b>SAFE
+CHOICE</b>
+for you. We accomplish this by backing up our open source Java products
+with technical support services that are delivered by the core
+developers themselves. We can help you to train your staff and provide
+you with support at every stage of the application lifecycle - from
+development and integration through deployment and maintenance. Visit
+the <a href="http://www.jboss.com/services/index">JBoss
+Services</a> page for more
+information.</p>
+
+</BODY>
+</HTML>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/build/pom.xml
===================================================================
--- branches/7.2.x/build/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/build/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,93 +0,0 @@
-<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">
-  <parent>
-    <artifactId>teiid-parent</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>teiid</artifactId>
-  <name>Build</name>
-  <description>Teiid Build</description>
-    <build>
-        <outputDirectory>target/kits</outputDirectory>
-        <resources>
-            <resource>
-                <directory>kits</directory>
-                <filtering>true</filtering>
-                <includes>
-                    <include>**/*.xml</include>
-                    <include>**/*.properties</include>
-                    <include>**/*.sh</include>
-                    <include>**/*.bat</include>
-                    <include>**/*.html</include>
-                </includes>
-            </resource>
-            <resource>
-                <directory>kits</directory>
-                <filtering>false</filtering>
-                <excludes>
-                    <exclude>**/*.xml</exclude>
-                    <exclude>**/*.properties</exclude>
-                    <exclude>**/*.sh</exclude>
-                    <exclude>**/*.bat</exclude>
-                    <exclude>**/*.html</exclude>
-                </excludes>
-            </resource>
-        </resources>
-        <pluginManagement>
-          <plugins>
-            <plugin>
-              <artifactId>maven-assembly-plugin</artifactId>
-            </plugin>
-          </plugins>
-        </pluginManagement>
-        <plugins>
-          <plugin>
-            <artifactId>maven-assembly-plugin</artifactId>
-
-            <configuration>
-              <descriptors>
-                <descriptor>assembly/client-jar.xml</descriptor>
-                <descriptor>assembly/jboss-container/dist.xml</descriptor>
-                <descriptor>assembly/adminshell/adminshell-dist.xml</descriptor>
-              </descriptors>
-            </configuration>
-
-            <executions>
-              <execution>
-                <id>create-assemblies</id>
-                <phase>package</phase>
-                <goals>
-                  <goal>single</goal>
-                </goals>
-              </execution>
-            </executions>
-          </plugin>
-        </plugins>
-    </build>
-    
-    <profiles>
-      <profile>
-        <!-- 
-            This profile is activated manually, as in "mvn ... -P release ..."
-  		  -->
-        <id>release</id>
-        <build>
-          <plugins>
-            <plugin>
-              <artifactId>maven-assembly-plugin</artifactId>
-              <configuration>
-                <descriptors>
-                  <descriptor>assembly/src.xml</descriptor>
-                  <descriptor>assembly/docs.xml</descriptor>
-                  <descriptor>assembly/client-jar.xml</descriptor>
-                  <descriptor>assembly/jboss-container/dist.xml</descriptor>
-                  <descriptor>assembly/adminshell/adminshell-dist.xml</descriptor>
-                </descriptors>
-              </configuration>
-            </plugin>
-          </plugins>
-        </build>
-      </profile>
-    </profiles>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/build/pom.xml (from rev 2708, branches/7.2.x/build/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/build/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/build/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,93 @@
+<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">
+  <parent>
+    <artifactId>teiid-parent</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>teiid</artifactId>
+  <name>Build</name>
+  <description>Teiid Build</description>
+    <build>
+        <outputDirectory>target/kits</outputDirectory>
+        <resources>
+            <resource>
+                <directory>kits</directory>
+                <filtering>true</filtering>
+                <includes>
+                    <include>**/*.xml</include>
+                    <include>**/*.properties</include>
+                    <include>**/*.sh</include>
+                    <include>**/*.bat</include>
+                    <include>**/*.html</include>
+                </includes>
+            </resource>
+            <resource>
+                <directory>kits</directory>
+                <filtering>false</filtering>
+                <excludes>
+                    <exclude>**/*.xml</exclude>
+                    <exclude>**/*.properties</exclude>
+                    <exclude>**/*.sh</exclude>
+                    <exclude>**/*.bat</exclude>
+                    <exclude>**/*.html</exclude>
+                </excludes>
+            </resource>
+        </resources>
+        <pluginManagement>
+          <plugins>
+            <plugin>
+              <artifactId>maven-assembly-plugin</artifactId>
+            </plugin>
+          </plugins>
+        </pluginManagement>
+        <plugins>
+          <plugin>
+            <artifactId>maven-assembly-plugin</artifactId>
+
+            <configuration>
+              <descriptors>
+                <descriptor>assembly/client-jar.xml</descriptor>
+                <descriptor>assembly/jboss-container/dist.xml</descriptor>
+                <descriptor>assembly/adminshell/adminshell-dist.xml</descriptor>
+              </descriptors>
+            </configuration>
+
+            <executions>
+              <execution>
+                <id>create-assemblies</id>
+                <phase>package</phase>
+                <goals>
+                  <goal>single</goal>
+                </goals>
+              </execution>
+            </executions>
+          </plugin>
+        </plugins>
+    </build>
+    
+    <profiles>
+      <profile>
+        <!-- 
+            This profile is activated manually, as in "mvn ... -P release ..."
+  		  -->
+        <id>release</id>
+        <build>
+          <plugins>
+            <plugin>
+              <artifactId>maven-assembly-plugin</artifactId>
+              <configuration>
+                <descriptors>
+                  <descriptor>assembly/src.xml</descriptor>
+                  <descriptor>assembly/docs.xml</descriptor>
+                  <descriptor>assembly/client-jar.xml</descriptor>
+                  <descriptor>assembly/jboss-container/dist.xml</descriptor>
+                  <descriptor>assembly/adminshell/adminshell-dist.xml</descriptor>
+                </descriptors>
+              </configuration>
+            </plugin>
+          </plugins>
+        </build>
+      </profile>
+    </profiles>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/cache-jbosscache/pom.xml
===================================================================
--- branches/7.2.x/cache-jbosscache/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/cache-jbosscache/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,29 +0,0 @@
-<?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">
-	<parent>
-		<artifactId>teiid-parent</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>teiid-cache-jbosscache</artifactId>
-	<name>JBoss Cache</name>
-	<description>JBossCache provider.</description>
-	<dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>    
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-engine</artifactId>
-            <scope>provided</scope>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.cache</groupId>
-			<artifactId>jbosscache-core</artifactId>
-            <scope>provided</scope>
-		</dependency>
-	</dependencies>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/cache-jbosscache/pom.xml (from rev 2708, branches/7.2.x/cache-jbosscache/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/cache-jbosscache/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/cache-jbosscache/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,34 @@
+<?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">
+	<parent>
+		<artifactId>teiid-parent</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>teiid-cache-jbosscache</artifactId>
+	<name>JBoss Cache</name>
+	<description>JBossCache provider.</description>
+	<dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>    
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-engine</artifactId>
+            <scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.cache</groupId>
+			<artifactId>jbosscache-core</artifactId>
+            <scope>provided</scope>
+		</dependency>
+        <dependency>
+            <groupId>org.jboss.man</groupId>
+            <artifactId>jboss-managed</artifactId>
+            <scope>provided</scope>
+        </dependency>        
+	</dependencies>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/client/pom.xml
===================================================================
--- branches/7.2.x/client/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/client/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,28 +0,0 @@
-<?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">
-	<parent>
-		<artifactId>teiid-parent</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>teiid-client</artifactId>
-	<name>Client</name>
-	<description>Contains the packages related to communication, administrative api,
-    sessioning and transport level messaging.</description>
-	<dependencies>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-			<type>test-jar</type>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.man</groupId>
-			<artifactId>jboss-managed</artifactId>
-		</dependency>
-	</dependencies>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/client/pom.xml (from rev 2708, branches/7.2.x/client/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/client/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/client/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,28 @@
+<?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">
+	<parent>
+		<artifactId>teiid-parent</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>teiid-client</artifactId>
+	<name>Client</name>
+	<description>Contains the packages related to communication, administrative api,
+    sessioning and transport level messaging.</description>
+	<dependencies>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-common-core</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-common-core</artifactId>
+			<type>test-jar</type>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.man</groupId>
+			<artifactId>jboss-managed</artifactId>
+		</dependency>
+	</dependencies>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/common-core/pom.xml
===================================================================
--- branches/7.2.x/common-core/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/common-core/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,51 +0,0 @@
-<?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">
-	<parent>
-		<artifactId>teiid-parent</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>teiid-common-core</artifactId>
-	<name>Common Core</name>
-	<description>Core shared library</description>
-	<build>
-		<plugins>
-			<plugin>
-				<artifactId>maven-antrun-plugin</artifactId>
-				<executions>
-					<execution>
-						<phase>process-resources</phase>
-						<configuration>
-							<tasks>
-								<tstamp />
-								<replace dir="${project.build.outputDirectory}" token="@build-date@" value="${DSTAMP}">
-									<include name="**/*.properties" />
-								</replace>
-							</tasks>
-						</configuration>
-						<goals>
-							<goal>run</goal>
-						</goals>
-					</execution>
-				</executions>
-			</plugin>
-		</plugins>
-		<resources>
-          <resource>
-            <directory>src/main/resources</directory>
-            <filtering>true</filtering>
-            <includes>
-              <include>**/*.properties</include>
-            </includes>
-          </resource>
-          <resource>
-            <directory>src/main/resources</directory>
-            <filtering>false</filtering>
-            <excludes>
-              <exclude>**/*.properties</exclude>
-            </excludes>
-          </resource>
-		</resources>
-	</build>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/common-core/pom.xml (from rev 2708, branches/7.2.x/common-core/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/common-core/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/common-core/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,51 @@
+<?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">
+	<parent>
+		<artifactId>teiid-parent</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>teiid-common-core</artifactId>
+	<name>Common Core</name>
+	<description>Core shared library</description>
+	<build>
+		<plugins>
+			<plugin>
+				<artifactId>maven-antrun-plugin</artifactId>
+				<executions>
+					<execution>
+						<phase>process-resources</phase>
+						<configuration>
+							<tasks>
+								<tstamp />
+								<replace dir="${project.build.outputDirectory}" token="@build-date@" value="${DSTAMP}">
+									<include name="**/*.properties" />
+								</replace>
+							</tasks>
+						</configuration>
+						<goals>
+							<goal>run</goal>
+						</goals>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+		<resources>
+          <resource>
+            <directory>src/main/resources</directory>
+            <filtering>true</filtering>
+            <includes>
+              <include>**/*.properties</include>
+            </includes>
+          </resource>
+          <resource>
+            <directory>src/main/resources</directory>
+            <filtering>false</filtering>
+            <excludes>
+              <exclude>**/*.properties</exclude>
+            </excludes>
+          </resource>
+		</resources>
+	</build>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/connectors/connector-file/pom.xml
===================================================================
--- branches/7.2.x/connectors/connector-file/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/connector-file/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,58 +0,0 @@
-<?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">
-    <parent>
-        <artifactId>connectors</artifactId>
-        <groupId>org.jboss.teiid</groupId>
-        <version>7.2.0.Final-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>connector-file</artifactId>
-    <groupId>org.jboss.teiid.connectors</groupId>
-    <name>File Connector</name>
-    <packaging>rar</packaging>
-    <description>This connector reads data from files.</description>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>javax.resource</groupId>
-            <artifactId>connector-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-    </dependencies>
-    <build>
-        <plugins>
-            <plugin>
-                <artifactId>maven-jar-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>build_jar</id>
-                        <phase>process-classes</phase>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                    </execution>
-                    <execution>
-                        <id>deploy_jar</id>
-                        <phase>package</phase>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                        <configuration>
-                            <classifier>lib</classifier>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-        </plugins>
-    </build>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/connectors/connector-file/pom.xml (from rev 2708, branches/7.2.x/connectors/connector-file/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/connector-file/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/connector-file/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,58 @@
+<?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">
+    <parent>
+        <artifactId>connectors</artifactId>
+        <groupId>org.jboss.teiid</groupId>
+        <version>7.2.0.Final</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>connector-file</artifactId>
+    <groupId>org.jboss.teiid.connectors</groupId>
+    <name>File Connector</name>
+    <packaging>rar</packaging>
+    <description>This connector reads data from files.</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.resource</groupId>
+            <artifactId>connector-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-jar-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>build_jar</id>
+                        <phase>process-classes</phase>
+                        <goals>
+                            <goal>jar</goal>
+                        </goals>
+                    </execution>
+                    <execution>
+                        <id>deploy_jar</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>jar</goal>
+                        </goals>
+                        <configuration>
+                            <classifier>lib</classifier>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/connectors/connector-ldap/pom.xml
===================================================================
--- branches/7.2.x/connectors/connector-ldap/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/connector-ldap/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,57 +0,0 @@
-<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">
-    <parent>
-        <artifactId>connectors</artifactId>
-        <groupId>org.jboss.teiid</groupId>
-        <version>7.2.0.Final-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>connector-ldap</artifactId>
-    <groupId>org.jboss.teiid.connectors</groupId>
-    <name>LDAP Connector</name>
-    <description>LDAP Connector</description>
-    <packaging>rar</packaging>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>javax.resource</groupId>
-            <artifactId>connector-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-    </dependencies>
-    <build>
-        <plugins>
-            <plugin>
-                <artifactId>maven-jar-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>build_jar</id>
-                        <phase>process-classes</phase>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                    </execution>
-                    <execution>
-                        <id>deploy_jar</id>
-                        <phase>package</phase>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                        <configuration>
-                            <classifier>lib</classifier>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-        </plugins>
-    </build>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/connectors/connector-ldap/pom.xml (from rev 2708, branches/7.2.x/connectors/connector-ldap/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/connector-ldap/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/connector-ldap/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,57 @@
+<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">
+    <parent>
+        <artifactId>connectors</artifactId>
+        <groupId>org.jboss.teiid</groupId>
+        <version>7.2.0.Final</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>connector-ldap</artifactId>
+    <groupId>org.jboss.teiid.connectors</groupId>
+    <name>LDAP Connector</name>
+    <description>LDAP Connector</description>
+    <packaging>rar</packaging>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.resource</groupId>
+            <artifactId>connector-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-jar-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>build_jar</id>
+                        <phase>process-classes</phase>
+                        <goals>
+                            <goal>jar</goal>
+                        </goals>
+                    </execution>
+                    <execution>
+                        <id>deploy_jar</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>jar</goal>
+                        </goals>
+                        <configuration>
+                            <classifier>lib</classifier>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/connectors/connector-salesforce/pom.xml
===================================================================
--- branches/7.2.x/connectors/connector-salesforce/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/connector-salesforce/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,70 +0,0 @@
-<?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">
-    <parent>
-        <artifactId>connectors</artifactId>
-        <groupId>org.jboss.teiid</groupId>
-        <version>7.2.0.Final-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>connector-salesforce</artifactId>
-    <groupId>org.jboss.teiid.connectors</groupId>
-    <name>Salesforce Connector</name>
-    <packaging>rar</packaging>
-    <description>Integrates the query engine with Salesforce.com.</description>
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid.connectors</groupId>
-            <artifactId>salesforce-api</artifactId>
-            <version>${project.version}</version>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid.connectors</groupId>
-            <artifactId>translator-salesforce</artifactId>
-            <version>${project.version}</version>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>javax.resource</groupId>
-            <artifactId>connector-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-    </dependencies>
-
-    <build>
-        <plugins>
-            <plugin>
-                <artifactId>maven-jar-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>build_jar</id>
-                        <phase>process-classes</phase>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                    </execution>
-                    <execution>
-                        <id>deploy_jar</id>
-                        <phase>package</phase>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                        <configuration>
-                            <classifier>lib</classifier>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-        </plugins>
-    </build>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/connectors/connector-salesforce/pom.xml (from rev 2708, branches/7.2.x/connectors/connector-salesforce/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/connector-salesforce/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/connector-salesforce/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,70 @@
+<?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">
+    <parent>
+        <artifactId>connectors</artifactId>
+        <groupId>org.jboss.teiid</groupId>
+        <version>7.2.0.Final</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>connector-salesforce</artifactId>
+    <groupId>org.jboss.teiid.connectors</groupId>
+    <name>Salesforce Connector</name>
+    <packaging>rar</packaging>
+    <description>Integrates the query engine with Salesforce.com.</description>
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid.connectors</groupId>
+            <artifactId>salesforce-api</artifactId>
+            <version>${project.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid.connectors</groupId>
+            <artifactId>translator-salesforce</artifactId>
+            <version>${project.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.resource</groupId>
+            <artifactId>connector-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-jar-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>build_jar</id>
+                        <phase>process-classes</phase>
+                        <goals>
+                            <goal>jar</goal>
+                        </goals>
+                    </execution>
+                    <execution>
+                        <id>deploy_jar</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>jar</goal>
+                        </goals>
+                        <configuration>
+                            <classifier>lib</classifier>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/connectors/connector-ws/pom.xml
===================================================================
--- branches/7.2.x/connectors/connector-ws/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/connector-ws/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,82 +0,0 @@
-<?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">
-    <parent>
-        <artifactId>connectors</artifactId>
-        <groupId>org.jboss.teiid</groupId>
-        <version>7.2.0.Final-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>connector-ws</artifactId>
-    <groupId>org.jboss.teiid.connectors</groupId>
-    <name>Web Service Connector</name>
-    <packaging>rar</packaging>
-    <description>This connector reads data from Web Services</description>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>javax.resource</groupId>
-            <artifactId>connector-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-  			<artifactId>cxf-rt-frontend-jaxws</artifactId>
-  			<version>2.2.2</version>
-            <scope>provided</scope>        
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-  			<artifactId>cxf-rt-transports-http</artifactId>
-  			<version>2.2.2</version>
-            <scope>provided</scope>        
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-  			<artifactId>cxf-rt-ws-security</artifactId>
-  			<version>2.2.2</version>
-            <scope>provided</scope>        
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-  			<artifactId>cxf-rt-ws-policy</artifactId>
-  			<version>2.2.2</version>
-            <scope>provided</scope>        
-        </dependency>
-    </dependencies>
-    <build>
-        <plugins>
-            <plugin>
-                <artifactId>maven-jar-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>build_jar</id>
-                        <phase>process-classes</phase>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                    </execution>
-                    <execution>
-                        <id>deploy_jar</id>
-                        <phase>package</phase>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                        <configuration>
-                            <classifier>lib</classifier>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-        </plugins>
-    </build>
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/connector-ws/pom.xml (from rev 2708, branches/7.2.x/connectors/connector-ws/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/connector-ws/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/connector-ws/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,82 @@
+<?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">
+    <parent>
+        <artifactId>connectors</artifactId>
+        <groupId>org.jboss.teiid</groupId>
+        <version>7.2.0.Final</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>connector-ws</artifactId>
+    <groupId>org.jboss.teiid.connectors</groupId>
+    <name>Web Service Connector</name>
+    <packaging>rar</packaging>
+    <description>This connector reads data from Web Services</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.resource</groupId>
+            <artifactId>connector-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+  			<artifactId>cxf-rt-frontend-jaxws</artifactId>
+  			<version>2.2.2</version>
+            <scope>provided</scope>        
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+  			<artifactId>cxf-rt-transports-http</artifactId>
+  			<version>2.2.2</version>
+            <scope>provided</scope>        
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+  			<artifactId>cxf-rt-ws-security</artifactId>
+  			<version>2.2.2</version>
+            <scope>provided</scope>        
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+  			<artifactId>cxf-rt-ws-policy</artifactId>
+  			<version>2.2.2</version>
+            <scope>provided</scope>        
+        </dependency>
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-jar-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>build_jar</id>
+                        <phase>process-classes</phase>
+                        <goals>
+                            <goal>jar</goal>
+                        </goals>
+                    </execution>
+                    <execution>
+                        <id>deploy_jar</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>jar</goal>
+                        </goals>
+                        <configuration>
+                            <classifier>lib</classifier>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/connectors/pom.xml
===================================================================
--- branches/7.2.x/connectors/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,94 +0,0 @@
-<?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">
-  <parent>
-    <artifactId>teiid-parent</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <groupId>org.jboss.teiid</groupId>
-  <artifactId>connectors</artifactId>
-  <packaging>pom</packaging>
-  <name>Connectors</name>
-  <description>This project is aggregator for all the supported connectors.</description>
-  <dependencies>
-          
-    <!--  Internal Test Dependencies -->
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-api</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-engine</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-client</artifactId>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-engine</artifactId>
-      <scope>test</scope>
-    </dependency>    
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-metadata</artifactId>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-metadata</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>        
-
-    <!-- External dependencies -->
-    <dependency>
-        <groupId>org.jboss</groupId>
-        <artifactId>jboss-vfs</artifactId>
-        <scope>test</scope>
-    </dependency>    
-    <dependency>
-        <groupId>org.jboss.man</groupId>
-        <artifactId>jboss-managed</artifactId>
-        <scope>test</scope>
-    </dependency>     
-    
-  </dependencies>
-  
-  <modules>
-    <module>translator-jdbc</module>
-    <module>translator-ldap</module>
-    
-    <module>translator-loopback</module>
-    <module>translator-file</module>
-    <module>translator-salesforce</module>
-    
-    <module>connector-file</module>
-    <module>connector-salesforce</module>
-    <module>connector-ldap</module>
-    <module>salesforce-api</module>
-    <module>connector-ws</module>
-
-    <module>sandbox</module>
-    
-    <module>translator-ws</module>
-  </modules>
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/pom.xml (from rev 2708, branches/7.2.x/connectors/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,94 @@
+<?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">
+  <parent>
+    <artifactId>teiid-parent</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.jboss.teiid</groupId>
+  <artifactId>connectors</artifactId>
+  <packaging>pom</packaging>
+  <name>Connectors</name>
+  <description>This project is aggregator for all the supported connectors.</description>
+  <dependencies>
+          
+    <!--  Internal Test Dependencies -->
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-api</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-engine</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-client</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-engine</artifactId>
+      <scope>test</scope>
+    </dependency>    
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-metadata</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-metadata</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>        
+
+    <!-- External dependencies -->
+    <dependency>
+        <groupId>org.jboss</groupId>
+        <artifactId>jboss-vfs</artifactId>
+        <scope>test</scope>
+    </dependency>    
+    <dependency>
+        <groupId>org.jboss.man</groupId>
+        <artifactId>jboss-managed</artifactId>
+        <scope>test</scope>
+    </dependency>     
+    
+  </dependencies>
+  
+  <modules>
+    <module>translator-jdbc</module>
+    <module>translator-ldap</module>
+    
+    <module>translator-loopback</module>
+    <module>translator-file</module>
+    <module>translator-salesforce</module>
+    
+    <module>connector-file</module>
+    <module>connector-salesforce</module>
+    <module>connector-ldap</module>
+    <module>salesforce-api</module>
+    <module>connector-ws</module>
+
+    <module>sandbox</module>
+    
+    <module>translator-ws</module>
+  </modules>
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/connectors/salesforce-api/pom.xml
===================================================================
--- branches/7.2.x/connectors/salesforce-api/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/salesforce-api/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,14 +0,0 @@
-<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">
-  <parent>
-    <artifactId>connectors</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>salesforce-api</artifactId>
-  <groupId>org.jboss.teiid.connectors</groupId>
-  <name>Salesforce API</name>
-  <description>The java API for the Salesforce.com partner web service API</description>
-    <dependencies>        
-  </dependencies>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/connectors/salesforce-api/pom.xml (from rev 2708, branches/7.2.x/connectors/salesforce-api/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/salesforce-api/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/salesforce-api/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,14 @@
+<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">
+  <parent>
+    <artifactId>connectors</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>salesforce-api</artifactId>
+  <groupId>org.jboss.teiid.connectors</groupId>
+  <name>Salesforce API</name>
+  <description>The java API for the Salesforce.com partner web service API</description>
+    <dependencies>        
+  </dependencies>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/connectors/sandbox/pom.xml
===================================================================
--- branches/7.2.x/connectors/sandbox/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/sandbox/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,17 +0,0 @@
-<?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">
-  <parent>
-    <artifactId>connectors</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <groupId>org.jboss.teiid.connectors</groupId>
-  <artifactId>sandbox</artifactId>
-  <packaging>pom</packaging>
-  <name>Sandbox</name>
-  <description>Experimental connectors in progress</description>
-  <modules>
-    <module>translator-yahoo</module>
-  </modules>
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/sandbox/pom.xml (from rev 2708, branches/7.2.x/connectors/sandbox/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/sandbox/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/sandbox/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,17 @@
+<?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">
+  <parent>
+    <artifactId>connectors</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.jboss.teiid.connectors</groupId>
+  <artifactId>sandbox</artifactId>
+  <packaging>pom</packaging>
+  <name>Sandbox</name>
+  <description>Experimental connectors in progress</description>
+  <modules>
+    <module>translator-yahoo</module>
+  </modules>
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/connectors/sandbox/translator-yahoo/pom.xml
===================================================================
--- branches/7.2.x/connectors/sandbox/translator-yahoo/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/sandbox/translator-yahoo/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,52 +0,0 @@
-<?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">
-    <parent>
-        <artifactId>sandbox</artifactId>
-        <groupId>org.jboss.teiid.connectors</groupId>
-        <version>7.2.0.Final-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>translator-yahoo</artifactId>
-    <groupId>org.jboss.teiid.connectors.sandbox</groupId>
-    <name>Yahoo Translator</name>
-    <description>Test translator used to query ticker symbols from Yahoo website</description>
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>javax.resource</groupId>
-            <artifactId>connector-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-    </dependencies>
-
-    <build>
-        <outputDirectory>target/classes</outputDirectory>
-        <resources>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>true</filtering>
-                <includes>
-                    <include>**/*.xml</include>
-                    <include>**/*.properties</include>
-                </includes>
-            </resource>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>false</filtering>
-                <excludes>
-                    <exclude>**/*.xml</exclude>
-                    <exclude>**/*.properties</exclude>
-                </excludes>
-            </resource>
-        </resources>
-    </build>
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/sandbox/translator-yahoo/pom.xml (from rev 2708, branches/7.2.x/connectors/sandbox/translator-yahoo/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/sandbox/translator-yahoo/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/sandbox/translator-yahoo/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,52 @@
+<?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">
+    <parent>
+        <artifactId>sandbox</artifactId>
+        <groupId>org.jboss.teiid.connectors</groupId>
+        <version>7.2.0.Final</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>translator-yahoo</artifactId>
+    <groupId>org.jboss.teiid.connectors.sandbox</groupId>
+    <name>Yahoo Translator</name>
+    <description>Test translator used to query ticker symbols from Yahoo website</description>
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.resource</groupId>
+            <artifactId>connector-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <outputDirectory>target/classes</outputDirectory>
+        <resources>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>true</filtering>
+                <includes>
+                    <include>**/*.xml</include>
+                    <include>**/*.properties</include>
+                </includes>
+            </resource>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>false</filtering>
+                <excludes>
+                    <exclude>**/*.xml</exclude>
+                    <exclude>**/*.properties</exclude>
+                </excludes>
+            </resource>
+        </resources>
+    </build>
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/connectors/translator-file/pom.xml
===================================================================
--- branches/7.2.x/connectors/translator-file/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-file/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,53 +0,0 @@
-<?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">
-    <parent>
-        <artifactId>connectors</artifactId>
-        <groupId>org.jboss.teiid</groupId>
-        <version>7.2.0.Final-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>translator-file</artifactId>
-    <groupId>org.jboss.teiid.connectors</groupId>
-    <name>File Translator</name>
-    <description>This translator provides access to the file system.</description>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>javax.resource</groupId>
-            <artifactId>connector-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-    </dependencies>
-
-    <build>
-        <outputDirectory>target/classes</outputDirectory>
-        <resources>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>true</filtering>
-                <includes>
-                    <include>**/*.xml</include>
-                    <include>**/*.properties</include>
-                </includes>
-            </resource>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>false</filtering>
-                <excludes>
-                    <exclude>**/*.xml</exclude>
-                    <exclude>**/*.properties</exclude>
-                </excludes>
-            </resource>
-        </resources>
-    </build>
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/translator-file/pom.xml (from rev 2708, branches/7.2.x/connectors/translator-file/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/translator-file/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-file/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,53 @@
+<?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">
+    <parent>
+        <artifactId>connectors</artifactId>
+        <groupId>org.jboss.teiid</groupId>
+        <version>7.2.0.Final</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>translator-file</artifactId>
+    <groupId>org.jboss.teiid.connectors</groupId>
+    <name>File Translator</name>
+    <description>This translator provides access to the file system.</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.resource</groupId>
+            <artifactId>connector-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <outputDirectory>target/classes</outputDirectory>
+        <resources>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>true</filtering>
+                <includes>
+                    <include>**/*.xml</include>
+                    <include>**/*.properties</include>
+                </includes>
+            </resource>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>false</filtering>
+                <excludes>
+                    <exclude>**/*.xml</exclude>
+                    <exclude>**/*.properties</exclude>
+                </excludes>
+            </resource>
+        </resources>
+    </build>
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/connectors/translator-jdbc/pom.xml
===================================================================
--- branches/7.2.x/connectors/translator-jdbc/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-jdbc/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,54 +0,0 @@
-<?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">
-  <parent>
-    <artifactId>connectors</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>translator-jdbc</artifactId>
-  <groupId>org.jboss.teiid.connectors</groupId>
-  <name>JDBC Translator</name>
-  
-  <description>This project contains translators for a JDBC source. Currently this is an aggregator for all the JDBC translators relational databases.</description>
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-          <groupId>javax.resource</groupId>
-          <artifactId>connector-api</artifactId>
-          <scope>provided</scope>
-        </dependency>       
-    </dependencies>
-    
-    <build>
-        <outputDirectory>target/classes</outputDirectory>
-        <resources>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>true</filtering>
-                <includes>
-                    <include>**/*.xml</include>
-                    <include>**/*.properties</include>
-                </includes>
-            </resource>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>false</filtering>
-                <excludes>
-                    <exclude>**/*.xml</exclude>
-                    <exclude>**/*.properties</exclude>
-                </excludes>
-            </resource>
-        </resources>
-    </build>    
-    
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/translator-jdbc/pom.xml (from rev 2708, branches/7.2.x/connectors/translator-jdbc/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/translator-jdbc/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-jdbc/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,54 @@
+<?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">
+  <parent>
+    <artifactId>connectors</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>translator-jdbc</artifactId>
+  <groupId>org.jboss.teiid.connectors</groupId>
+  <name>JDBC Translator</name>
+  
+  <description>This project contains translators for a JDBC source. Currently this is an aggregator for all the JDBC translators relational databases.</description>
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+          <groupId>javax.resource</groupId>
+          <artifactId>connector-api</artifactId>
+          <scope>provided</scope>
+        </dependency>       
+    </dependencies>
+    
+    <build>
+        <outputDirectory>target/classes</outputDirectory>
+        <resources>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>true</filtering>
+                <includes>
+                    <include>**/*.xml</include>
+                    <include>**/*.properties</include>
+                </includes>
+            </resource>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>false</filtering>
+                <excludes>
+                    <exclude>**/*.xml</exclude>
+                    <exclude>**/*.properties</exclude>
+                </excludes>
+            </resource>
+        </resources>
+    </build>    
+    
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/connectors/translator-ldap/pom.xml
===================================================================
--- branches/7.2.x/connectors/translator-ldap/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-ldap/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,52 +0,0 @@
-<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">
-  <parent>
-    <artifactId>connectors</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>translator-ldap</artifactId>
-  <groupId>org.jboss.teiid.connectors</groupId>
-  <name>LDAP Translator</name>
-  <description>LDAP Translator</description>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-          <groupId>javax.resource</groupId>
-          <artifactId>connector-api</artifactId>
-          <scope>provided</scope>
-        </dependency>        
-    </dependencies>
-    
-    <build>
-        <outputDirectory>target/classes</outputDirectory>
-        <resources>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>true</filtering>
-                <includes>
-                    <include>**/*.xml</include>
-                    <include>**/*.properties</include>
-                </includes>
-            </resource>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>false</filtering>
-                <excludes>
-                    <exclude>**/*.xml</exclude>
-                    <exclude>**/*.properties</exclude>
-                </excludes>
-            </resource>
-        </resources>
-    </build>       
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/translator-ldap/pom.xml (from rev 2708, branches/7.2.x/connectors/translator-ldap/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/translator-ldap/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-ldap/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,52 @@
+<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">
+  <parent>
+    <artifactId>connectors</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>translator-ldap</artifactId>
+  <groupId>org.jboss.teiid.connectors</groupId>
+  <name>LDAP Translator</name>
+  <description>LDAP Translator</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+          <groupId>javax.resource</groupId>
+          <artifactId>connector-api</artifactId>
+          <scope>provided</scope>
+        </dependency>        
+    </dependencies>
+    
+    <build>
+        <outputDirectory>target/classes</outputDirectory>
+        <resources>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>true</filtering>
+                <includes>
+                    <include>**/*.xml</include>
+                    <include>**/*.properties</include>
+                </includes>
+            </resource>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>false</filtering>
+                <excludes>
+                    <exclude>**/*.xml</exclude>
+                    <exclude>**/*.properties</exclude>
+                </excludes>
+            </resource>
+        </resources>
+    </build>       
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/connectors/translator-loopback/pom.xml
===================================================================
--- branches/7.2.x/connectors/translator-loopback/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-loopback/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,53 +0,0 @@
-<?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">
-    <parent>
-        <artifactId>connectors</artifactId>
-        <groupId>org.jboss.teiid</groupId>
-        <version>7.2.0.Final-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>translator-loopback</artifactId>
-    <groupId>org.jboss.teiid.connectors</groupId>
-    <name>Loopback Translator</name>
-    <description>Loopback Translator</description>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>javax.resource</groupId>
-            <artifactId>connector-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-    </dependencies>
-    
-    <build>
-        <outputDirectory>target/classes</outputDirectory>
-        <resources>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>true</filtering>
-                <includes>
-                    <include>**/*.xml</include>
-                    <include>**/*.properties</include>
-                </includes>
-            </resource>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>false</filtering>
-                <excludes>
-                    <exclude>**/*.xml</exclude>
-                    <exclude>**/*.properties</exclude>
-                </excludes>
-            </resource>
-        </resources>
-    </build>       
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/translator-loopback/pom.xml (from rev 2708, branches/7.2.x/connectors/translator-loopback/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/translator-loopback/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-loopback/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,53 @@
+<?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">
+    <parent>
+        <artifactId>connectors</artifactId>
+        <groupId>org.jboss.teiid</groupId>
+        <version>7.2.0.Final</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>translator-loopback</artifactId>
+    <groupId>org.jboss.teiid.connectors</groupId>
+    <name>Loopback Translator</name>
+    <description>Loopback Translator</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.resource</groupId>
+            <artifactId>connector-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+    
+    <build>
+        <outputDirectory>target/classes</outputDirectory>
+        <resources>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>true</filtering>
+                <includes>
+                    <include>**/*.xml</include>
+                    <include>**/*.properties</include>
+                </includes>
+            </resource>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>false</filtering>
+                <excludes>
+                    <exclude>**/*.xml</exclude>
+                    <exclude>**/*.properties</exclude>
+                </excludes>
+            </resource>
+        </resources>
+    </build>       
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/pom.xml
===================================================================
--- branches/7.2.x/connectors/translator-salesforce/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,57 +0,0 @@
-<?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">
-	<parent>
-		<artifactId>connectors</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>translator-salesforce</artifactId>
-	<groupId>org.jboss.teiid.connectors</groupId>
-	<name>Salesforce Translator</name>
-	<description>Integrates the query engine with Salesforce.com.</description>
-	<dependencies>
-        <dependency>
-          <groupId>org.jboss.teiid</groupId>
-          <artifactId>teiid-api</artifactId>
-          <scope>provided</scope>
-        </dependency>
-        <dependency>
-          <groupId>org.jboss.teiid</groupId>
-          <artifactId>teiid-common-core</artifactId>
-          <scope>provided</scope>
-        </dependency>
-        <dependency>
-			<groupId>org.jboss.teiid.connectors</groupId>
-			<artifactId>salesforce-api</artifactId>
-			<version>${project.version}</version>
-		</dependency>
-        <dependency>
-            <groupId>javax.resource</groupId>
-            <artifactId>connector-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-    </dependencies>
-    
-    <build>
-        <outputDirectory>target/classes</outputDirectory>
-        <resources>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>true</filtering>
-                <includes>
-                    <include>**/*.xml</include>
-                    <include>**/*.properties</include>
-                </includes>
-            </resource>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>false</filtering>
-                <excludes>
-                    <exclude>**/*.xml</exclude>
-                    <exclude>**/*.properties</exclude>
-                </excludes>
-            </resource>
-        </resources>
-    </build>    
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/pom.xml (from rev 2708, branches/7.2.x/connectors/translator-salesforce/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,57 @@
+<?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">
+	<parent>
+		<artifactId>connectors</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>translator-salesforce</artifactId>
+	<groupId>org.jboss.teiid.connectors</groupId>
+	<name>Salesforce Translator</name>
+	<description>Integrates the query engine with Salesforce.com.</description>
+	<dependencies>
+        <dependency>
+          <groupId>org.jboss.teiid</groupId>
+          <artifactId>teiid-api</artifactId>
+          <scope>provided</scope>
+        </dependency>
+        <dependency>
+          <groupId>org.jboss.teiid</groupId>
+          <artifactId>teiid-common-core</artifactId>
+          <scope>provided</scope>
+        </dependency>
+        <dependency>
+			<groupId>org.jboss.teiid.connectors</groupId>
+			<artifactId>salesforce-api</artifactId>
+			<version>${project.version}</version>
+		</dependency>
+        <dependency>
+            <groupId>javax.resource</groupId>
+            <artifactId>connector-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+    
+    <build>
+        <outputDirectory>target/classes</outputDirectory>
+        <resources>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>true</filtering>
+                <includes>
+                    <include>**/*.xml</include>
+                    <include>**/*.properties</include>
+                </includes>
+            </resource>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>false</filtering>
+                <excludes>
+                    <exclude>**/*.xml</exclude>
+                    <exclude>**/*.properties</exclude>
+                </excludes>
+            </resource>
+        </resources>
+    </build>    
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/QueryExecutionImpl.java
===================================================================
--- branches/7.2.x/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/QueryExecutionImpl.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/QueryExecutionImpl.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,369 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.translator.salesforce.execution;
-
-import java.sql.Timestamp;
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.resource.ResourceException;
-import javax.xml.namespace.QName;
-
-import org.teiid.language.AggregateFunction;
-import org.teiid.language.Join;
-import org.teiid.language.QueryExpression;
-import org.teiid.language.Select;
-import org.teiid.language.TableReference;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.AbstractMetadataRecord;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.RuntimeMetadata;
-import org.teiid.metadata.Table;
-import org.teiid.translator.DataNotAvailableException;
-import org.teiid.translator.ExecutionContext;
-import org.teiid.translator.ResultSetExecution;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.salesforce.SalesForcePlugin;
-import org.teiid.translator.salesforce.SalesforceConnection;
-import org.teiid.translator.salesforce.Util;
-import org.teiid.translator.salesforce.execution.visitors.JoinQueryVisitor;
-import org.teiid.translator.salesforce.execution.visitors.SelectVisitor;
-import org.w3c.dom.Element;
-
-import com.sforce.soap.partner.QueryResult;
-import com.sforce.soap.partner.sobject.SObject;
-
-public class QueryExecutionImpl implements ResultSetExecution {
-
-	private SalesforceConnection connection;
-
-	private RuntimeMetadata metadata;
-
-	private ExecutionContext context;
-
-	
-	private SelectVisitor visitor;
-	
-	private QueryResult results;
-	
-	private List<List<Object>> resultBatch;
-
-	// Identifying values
-	private String connectionIdentifier;
-
-	private String connectorIdentifier;
-
-	private String requestIdentifier;
-
-	private String partIdentifier;
-
-	private String logPreamble;
-	
-	private QueryExpression query;
-	
-	Map<String, Map<String,Integer>> sObjectToResponseField = new HashMap<String, Map<String,Integer>>();
-	
-	private int topResultIndex = 0;
-	
-	public QueryExecutionImpl(QueryExpression command, SalesforceConnection connection, RuntimeMetadata metadata, ExecutionContext context) {
-		this.connection = connection;
-		this.metadata = metadata;
-		this.context = context;
-		this.query = command;
-
-		connectionIdentifier = context.getConnectionIdentifier();
-		connectorIdentifier = context.getConnectorIdentifier();
-		requestIdentifier = context.getRequestIdentifier();
-		partIdentifier = context.getPartIdentifier();
-	}
-
-	public void cancel() throws TranslatorException {
-		LogManager.logDetail(LogConstants.CTX_CONNECTOR, SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.cancel"));//$NON-NLS-1$
-	}
-
-	public void close() {
-		LogManager.logDetail(LogConstants.CTX_CONNECTOR, SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.close")); //$NON-NLS-1$
-	}
-
-	@Override
-	public void execute() throws TranslatorException {
-		try {
-			LogManager.logDetail(LogConstants.CTX_CONNECTOR, getLogPreamble(), "Incoming Query:", query); //$NON-NLS-1$
-			List<TableReference> from = ((Select)query).getFrom();
-			String finalQuery;
-			if(from.get(0) instanceof Join) {
-				visitor = new JoinQueryVisitor(metadata);
-				visitor.visitNode(query);
-				finalQuery = visitor.getQuery().trim();
-				LogManager.logDetail(LogConstants.CTX_CONNECTOR, getLogPreamble(), "Executing Query:", finalQuery); //$NON-NLS-1$
-				
-				results = connection.query(finalQuery, this.context.getBatchSize(), visitor.getQueryAll());
-			} else {
-				visitor = new SelectVisitor(metadata);
-				visitor.visitNode(query);
-				if(visitor.canRetrieve()) {
-					results = connection.retrieve(visitor.getRetrieveFieldList(),
-							visitor.getTableName(), visitor.getIdInCriteria());
-				} else {
-					finalQuery = visitor.getQuery().trim();
-					LogManager.logDetail(LogConstants.CTX_CONNECTOR,  getLogPreamble(), "Executing Query:", finalQuery); //$NON-NLS-1$
-					results = connection.query(finalQuery, this.context.getBatchSize(), visitor.getQueryAll());
-				}
-			}
-		} catch (ResourceException e) {
-			throw new TranslatorException(e);
-		}
-	}
-	
-	@SuppressWarnings("unchecked")
-	@Override
-	public List next() throws TranslatorException, DataNotAvailableException {
-		List<?> result;
-		if (query.getProjectedQuery().getDerivedColumns().get(0)
-				.getExpression() instanceof AggregateFunction) {
-			if (results == null) {
-				return null;
-			}
-			result = Arrays.asList(results.getSize());
-			results = null;
-			
-		} else {
-			result = getRow(results);
-		}
-		return result;
-	}
-
-	private List<Object> getRow(QueryResult result) throws TranslatorException {
-		List<Object> row;
-		if(null == resultBatch) {
-			loadBatch();
-		}
-		if(resultBatch.size() == topResultIndex) {
-			row = null;
-		} else {
-			row = resultBatch.get(topResultIndex);
-			topResultIndex++;
-			if(resultBatch.size() == topResultIndex) {
-				if(!result.isDone()) {
-					loadBatch();
-				}
-			}
-			
-		}
-		return row;
-	}
-
-		private void loadBatch() throws TranslatorException {
-			try {
-				if(null != resultBatch) { // if we have an old batch, then we have to get new results
-					results = connection.queryMore(results.getQueryLocator(), context.getBatchSize());
-				}
-				resultBatch = new ArrayList<List<Object>>();
-					
-				for(SObject sObject : results.getRecords()) {
-					List<Object[]> result = getObjectData(sObject);
-					for(Iterator<Object[]> i = result.iterator(); i.hasNext(); ) {
-						resultBatch.add(Arrays.asList(i.next()));
-					}
-				}
-			} catch (ResourceException e) {
-				throw new TranslatorException(e);
-			}
-		}
-
-		private List<Object[]> getObjectData(SObject sObject) throws TranslatorException {
-			List<Object> topFields = sObject.getAny();
-			logAndMapFields(sObject.getType(), topFields);
-			List<Object[]> result = new ArrayList<Object[]>();
-			for(int i = 0; i < topFields.size(); i++) {
-				Element element = (Element) topFields.get(i);
-				QName qName = new QName(element.getNamespaceURI(), element.getLocalName());
-				if(null != qName) {
-					String type = qName.getLocalPart();
-					if(type.equals("sObject")) { //$NON-NLS-1$
-						//SObject parent = (SObject)element.;
-						//result.addAll(getObjectData(parent));
-					} else if(type.equals("QueryResult")) { //$NON-NLS-1$
-						//QueryResult subResult = (QueryResult)element.getValue();
-						//for(int resultIndex = 0; resultIndex < subResult.getSize(); resultIndex++) {
-						//	SObject subObject = subResult.getRecords().get(resultIndex);
-						//	result.addAll(getObjectData(subObject));
-						//}
-					}
-				}
-			}
-			return extractDataFromFields(sObject, topFields, result);
-			
-		}
-
-		private List<Object[]> extractDataFromFields(SObject sObject,
-			List<Object> fields, List<Object[]> result) throws TranslatorException {
-			Map<String,Integer> fieldToIndexMap = sObjectToResponseField.get(sObject.getType());
-			for (int j = 0; j < visitor.getSelectSymbolCount(); j++) {
-				Column element = visitor.getSelectSymbolMetadata(j);
-				AbstractMetadataRecord parent = element.getParent();
-				Table table;
-				if(parent instanceof Table) {
-					table = (Table)parent;
-				} else {
-					parent = parent.getParent();
-					if(parent instanceof Table) {
-						table = (Table)parent;
-					} else {
-						throw new TranslatorException("Could not resolve Table for column " + element.getName()); //$NON-NLS-1$
-					}
-				}
-				if(table.getNameInSource().equals(sObject.getType())) {
-					Integer index = fieldToIndexMap.get(element.getNameInSource());
-					// id gets dropped from the result if it is not the
-					// first field in the querystring. Add it back in.
-					if (null == index) {
-						if (element.getNameInSource().equalsIgnoreCase("id")) { //$NON-NLS-1$
-							setValueInColumn(j, sObject.getId(), result);
-						} else {
-							throw new TranslatorException(SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.missing.field")+ element.getNameInSource()); //$NON-NLS-1$
-						}
-					} else {
-						Object cell;
-						cell = getCellDatum(element, (Element)fields.get(index));
-						setValueInColumn(j, cell, result);
-					}
-				}
-			}
-			return result;
-	}
-		
-	private void setValueInColumn(int columnIndex, Object value, List<Object[]> result) {
-		if(result.isEmpty()) {
-			Object[] row = new Object[visitor.getSelectSymbolCount()];
-			result.add(row);
-		}
-		Iterator<Object[]> iter = result.iterator();
-		while (iter.hasNext()) {
-			Object[] row = iter.next();
-			row[columnIndex] = value;
-		}	
-	}
-
-	/**
-	 * Load the map of response field names to index.
-	 * @param fields
-	 * @throws TranslatorException 
-	 */
-	private void logAndMapFields(String sObjectName,
-			List<Object> fields) throws TranslatorException {
-		if (!sObjectToResponseField.containsKey(sObjectName)) {
-			logFields(sObjectName, fields);
-			Map<String, Integer> responseFieldToIndexMap;
-			responseFieldToIndexMap = new HashMap<String, Integer>();
-			for (int x = 0; x < fields.size(); x++) {
-				Element element = (Element) fields.get(x);
-				responseFieldToIndexMap.put(element.getLocalName(), x);
-			}
-			sObjectToResponseField.put(sObjectName, responseFieldToIndexMap);
-		}
-	}
-
-	private void logFields(String sObjectName, List<Object> fields) throws TranslatorException {
-		LogManager.logDetail(LogConstants.CTX_CONNECTOR, "SalesForce Object Name = " + sObjectName); //$NON-NLS-1$
-		LogManager.logDetail(LogConstants.CTX_CONNECTOR, "FieldCount = " + fields.size()); //$NON-NLS-1$
-		for(int i = 0; i < fields.size(); i++) {
-			Element element;
-			element = (Element) fields.get(i);
-			LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Field # " + i + " is " + element.getLocalName()); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-		
-	}
-
-	@SuppressWarnings("unchecked")
-	private Object getCellDatum(Column element, Element elem) throws TranslatorException {
-		if(!element.getNameInSource().equals(elem.getLocalName())) {
-			throw new TranslatorException(SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.column.mismatch1") + element.getNameInSource() + SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.column.mismatch2") + elem.getLocalName()); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-		String value = elem.getTextContent();
-		Object result = null;
-		Class type = element.getJavaType();
-		
-		if(type.equals(String.class)) {
-			result = value;
-		}
-		else if (type.equals(Boolean.class)) {
-			result = Boolean.valueOf(value);
-		} else if (type.equals(Double.class)) {
-			if (null != value) {
-				if(!value.isEmpty()) {
-					result = Double.valueOf(value);
-				}
-			}
-		} else if (type.equals(Integer.class)) {
-			if (null != value) {
-				if(!value.isEmpty()) {
-					result = Integer.valueOf(value);
-				}
-			}
-		} else if (type.equals(java.sql.Date.class)) {
-			if (null != value) {
-				if(!value.isEmpty()) {
-					result = java.sql.Date.valueOf(value);
-				}
-			}
-		} else if (type.equals(java.sql.Timestamp.class)) {
-			if (null != value) {
-				if(!value.isEmpty()) { 
-					try {
-						Date date = Util.getSalesforceDateTimeFormat().parse(value);
-						result = new Timestamp(date.getTime());
-					} catch (ParseException e) {
-						throw new TranslatorException(e, SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.datatime.parse") + value); //$NON-NLS-1$
-					}
-				}
-			}
-		} else {
-			result = value;
-		}
-		return result;
-	}
-
-
-	private String getLogPreamble() {
-		if (null == logPreamble) {
-			StringBuffer preamble = new StringBuffer();
-			preamble.append(connectorIdentifier);
-			preamble.append('.');
-			preamble.append(connectionIdentifier);
-			preamble.append('.');
-			preamble.append(requestIdentifier);
-			preamble.append('.');
-			preamble.append(partIdentifier);
-			preamble.append(": "); //$NON-NLS-1$
-			logPreamble = preamble.toString();
-		}
-		return logPreamble;
-	}
-}

Copied: tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/QueryExecutionImpl.java (from rev 2707, branches/7.2.x/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/QueryExecutionImpl.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/QueryExecutionImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/QueryExecutionImpl.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,373 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.translator.salesforce.execution;
+
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.resource.ResourceException;
+import javax.xml.namespace.QName;
+
+import org.teiid.language.AggregateFunction;
+import org.teiid.language.Join;
+import org.teiid.language.QueryExpression;
+import org.teiid.language.Select;
+import org.teiid.language.TableReference;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.metadata.AbstractMetadataRecord;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.metadata.Table;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.salesforce.SalesForcePlugin;
+import org.teiid.translator.salesforce.SalesforceConnection;
+import org.teiid.translator.salesforce.Util;
+import org.teiid.translator.salesforce.execution.visitors.JoinQueryVisitor;
+import org.teiid.translator.salesforce.execution.visitors.SelectVisitor;
+import org.w3c.dom.Element;
+
+import com.sforce.soap.partner.QueryResult;
+import com.sforce.soap.partner.sobject.SObject;
+
+public class QueryExecutionImpl implements ResultSetExecution {
+
+	private SalesforceConnection connection;
+
+	private RuntimeMetadata metadata;
+
+	private ExecutionContext context;
+
+	
+	private SelectVisitor visitor;
+	
+	private QueryResult results;
+	
+	private List<List<Object>> resultBatch;
+
+	// Identifying values
+	private String connectionIdentifier;
+
+	private String connectorIdentifier;
+
+	private String requestIdentifier;
+
+	private String partIdentifier;
+
+	private String logPreamble;
+	
+	private QueryExpression query;
+	
+	Map<String, Map<String,Integer>> sObjectToResponseField = new HashMap<String, Map<String,Integer>>();
+	
+	private int topResultIndex = 0;
+	
+	public QueryExecutionImpl(QueryExpression command, SalesforceConnection connection, RuntimeMetadata metadata, ExecutionContext context) {
+		this.connection = connection;
+		this.metadata = metadata;
+		this.context = context;
+		this.query = command;
+
+		connectionIdentifier = context.getConnectionIdentifier();
+		connectorIdentifier = context.getConnectorIdentifier();
+		requestIdentifier = context.getRequestIdentifier();
+		partIdentifier = context.getPartIdentifier();
+	}
+
+	public void cancel() throws TranslatorException {
+		LogManager.logDetail(LogConstants.CTX_CONNECTOR, SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.cancel"));//$NON-NLS-1$
+	}
+
+	public void close() {
+		LogManager.logDetail(LogConstants.CTX_CONNECTOR, SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.close")); //$NON-NLS-1$
+	}
+
+	@Override
+	public void execute() throws TranslatorException {
+		try {
+			LogManager.logDetail(LogConstants.CTX_CONNECTOR, getLogPreamble(), "Incoming Query:", query); //$NON-NLS-1$
+			List<TableReference> from = ((Select)query).getFrom();
+			String finalQuery;
+			if(from.get(0) instanceof Join) {
+				visitor = new JoinQueryVisitor(metadata);
+				visitor.visitNode(query);
+				finalQuery = visitor.getQuery().trim();
+				LogManager.logDetail(LogConstants.CTX_CONNECTOR, getLogPreamble(), "Executing Query:", finalQuery); //$NON-NLS-1$
+				
+				results = connection.query(finalQuery, this.context.getBatchSize(), visitor.getQueryAll());
+			} else {
+				visitor = new SelectVisitor(metadata);
+				visitor.visitNode(query);
+				if(visitor.canRetrieve()) {
+					results = connection.retrieve(visitor.getRetrieveFieldList(),
+							visitor.getTableName(), visitor.getIdInCriteria());
+				} else {
+					finalQuery = visitor.getQuery().trim();
+					LogManager.logDetail(LogConstants.CTX_CONNECTOR,  getLogPreamble(), "Executing Query:", finalQuery); //$NON-NLS-1$
+					results = connection.query(finalQuery, this.context.getBatchSize(), visitor.getQueryAll());
+				}
+			}
+		} catch (ResourceException e) {
+			throw new TranslatorException(e);
+		}
+	}
+	
+	@SuppressWarnings("unchecked")
+	@Override
+	public List next() throws TranslatorException, DataNotAvailableException {
+		List<?> result;
+		if (query.getProjectedQuery().getDerivedColumns().get(0)
+				.getExpression() instanceof AggregateFunction) {
+			if (results == null) {
+				return null;
+			}
+			result = Arrays.asList(results.getSize());
+			results = null;
+			
+		} else {
+			result = getRow(results);
+		}
+		return result;
+	}
+
+	private List<Object> getRow(QueryResult result) throws TranslatorException {
+		List<Object> row;
+		if(null == resultBatch) {
+			loadBatch();
+		}
+		if(resultBatch.size() == topResultIndex) {
+			row = null;
+		} else {
+			row = resultBatch.get(topResultIndex);
+			topResultIndex++;
+			if(resultBatch.size() == topResultIndex) {
+				if(!result.isDone()) {
+					loadBatch();
+				}
+			}
+			
+		}
+		return row;
+	}
+
+		private void loadBatch() throws TranslatorException {
+			try {
+				if(null != resultBatch) { // if we have an old batch, then we have to get new results
+					results = connection.queryMore(results.getQueryLocator(), context.getBatchSize());
+				}
+				resultBatch = new ArrayList<List<Object>>();
+				topResultIndex = 0;
+				for(SObject sObject : results.getRecords()) {
+					List<Object[]> result = getObjectData(sObject);
+					for(Iterator<Object[]> i = result.iterator(); i.hasNext(); ) {
+						resultBatch.add(Arrays.asList(i.next()));
+					}
+				}
+			} catch (ResourceException e) {
+				throw new TranslatorException(e);
+			}
+		}
+
+		private List<Object[]> getObjectData(SObject sObject) throws TranslatorException {
+			List<Object> topFields = sObject.getAny();
+			logAndMapFields(sObject.getType(), topFields);
+			List<Object[]> result = new ArrayList<Object[]>();
+			for(int i = 0; i < topFields.size(); i++) {
+				Element element = (Element) topFields.get(i);
+				QName qName = new QName(element.getNamespaceURI(), element.getLocalName());
+				if(null != qName) {
+					String type = qName.getLocalPart();
+					if(type.equals("sObject")) { //$NON-NLS-1$
+						//SObject parent = (SObject)element.;
+						//result.addAll(getObjectData(parent));
+					} else if(type.equals("QueryResult")) { //$NON-NLS-1$
+						//QueryResult subResult = (QueryResult)element.getValue();
+						//for(int resultIndex = 0; resultIndex < subResult.getSize(); resultIndex++) {
+						//	SObject subObject = subResult.getRecords().get(resultIndex);
+						//	result.addAll(getObjectData(subObject));
+						//}
+					}
+				}
+			}
+			return extractDataFromFields(sObject, topFields, result);
+			
+		}
+
+		private List<Object[]> extractDataFromFields(SObject sObject,
+			List<Object> fields, List<Object[]> result) throws TranslatorException {
+			Map<String,Integer> fieldToIndexMap = sObjectToResponseField.get(sObject.getType());
+			for (int j = 0; j < visitor.getSelectSymbolCount(); j++) {
+				Column element = visitor.getSelectSymbolMetadata(j);
+				AbstractMetadataRecord parent = element.getParent();
+				Table table;
+				if(parent instanceof Table) {
+					table = (Table)parent;
+				} else {
+					parent = parent.getParent();
+					if(parent instanceof Table) {
+						table = (Table)parent;
+					} else {
+						throw new TranslatorException("Could not resolve Table for column " + element.getName()); //$NON-NLS-1$
+					}
+				}
+				if(table.getNameInSource().equals(sObject.getType())) {
+					Integer index = fieldToIndexMap.get(element.getNameInSource());
+					// id gets dropped from the result if it is not the
+					// first field in the querystring. Add it back in.
+					if (null == index) {
+						if (element.getNameInSource().equalsIgnoreCase("id")) { //$NON-NLS-1$
+							setValueInColumn(j, sObject.getId(), result);
+						} else {
+							throw new TranslatorException(SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.missing.field")+ element.getNameInSource()); //$NON-NLS-1$
+						}
+					} else {
+						Object cell;
+						cell = getCellDatum(element, (Element)fields.get(index));
+						setValueInColumn(j, cell, result);
+					}
+				}
+			}
+			return result;
+	}
+		
+	private void setValueInColumn(int columnIndex, Object value, List<Object[]> result) {
+		if(result.isEmpty()) {
+			Object[] row = new Object[visitor.getSelectSymbolCount()];
+			result.add(row);
+		}
+		Iterator<Object[]> iter = result.iterator();
+		while (iter.hasNext()) {
+			Object[] row = iter.next();
+			row[columnIndex] = value;
+		}	
+	}
+
+	/**
+	 * Load the map of response field names to index.
+	 * @param fields
+	 * @throws TranslatorException 
+	 */
+	private void logAndMapFields(String sObjectName,
+			List<Object> fields) throws TranslatorException {
+		if (!sObjectToResponseField.containsKey(sObjectName)) {
+			logFields(sObjectName, fields);
+			Map<String, Integer> responseFieldToIndexMap;
+			responseFieldToIndexMap = new HashMap<String, Integer>();
+			for (int x = 0; x < fields.size(); x++) {
+				Element element = (Element) fields.get(x);
+				responseFieldToIndexMap.put(element.getLocalName(), x);
+			}
+			sObjectToResponseField.put(sObjectName, responseFieldToIndexMap);
+		}
+	}
+
+	private void logFields(String sObjectName, List<Object> fields) throws TranslatorException {
+		if (!LogManager.isMessageToBeRecorded(LogConstants.CTX_CONNECTOR, MessageLevel.DETAIL)) {
+			return;
+		}
+		LogManager.logDetail(LogConstants.CTX_CONNECTOR, "SalesForce Object Name = " + sObjectName); //$NON-NLS-1$
+		LogManager.logDetail(LogConstants.CTX_CONNECTOR, "FieldCount = " + fields.size()); //$NON-NLS-1$
+		for(int i = 0; i < fields.size(); i++) {
+			Element element;
+			element = (Element) fields.get(i);
+			LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Field # " + i + " is " + element.getLocalName()); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+		
+	}
+
+	@SuppressWarnings("unchecked")
+	private Object getCellDatum(Column element, Element elem) throws TranslatorException {
+		if(!element.getNameInSource().equals(elem.getLocalName())) {
+			throw new TranslatorException(SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.column.mismatch1") + element.getNameInSource() + SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.column.mismatch2") + elem.getLocalName()); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+		String value = elem.getTextContent();
+		Object result = null;
+		Class type = element.getJavaType();
+		
+		if(type.equals(String.class)) {
+			result = value;
+		}
+		else if (type.equals(Boolean.class)) {
+			result = Boolean.valueOf(value);
+		} else if (type.equals(Double.class)) {
+			if (null != value) {
+				if(!value.isEmpty()) {
+					result = Double.valueOf(value);
+				}
+			}
+		} else if (type.equals(Integer.class)) {
+			if (null != value) {
+				if(!value.isEmpty()) {
+					result = Integer.valueOf(value);
+				}
+			}
+		} else if (type.equals(java.sql.Date.class)) {
+			if (null != value) {
+				if(!value.isEmpty()) {
+					result = java.sql.Date.valueOf(value);
+				}
+			}
+		} else if (type.equals(java.sql.Timestamp.class)) {
+			if (null != value) {
+				if(!value.isEmpty()) { 
+					try {
+						Date date = Util.getSalesforceDateTimeFormat().parse(value);
+						result = new Timestamp(date.getTime());
+					} catch (ParseException e) {
+						throw new TranslatorException(e, SalesForcePlugin.Util.getString("SalesforceQueryExecutionImpl.datatime.parse") + value); //$NON-NLS-1$
+					}
+				}
+			}
+		} else {
+			result = value;
+		}
+		return result;
+	}
+
+
+	private String getLogPreamble() {
+		if (null == logPreamble) {
+			StringBuffer preamble = new StringBuffer();
+			preamble.append(connectorIdentifier);
+			preamble.append('.');
+			preamble.append(connectionIdentifier);
+			preamble.append('.');
+			preamble.append(requestIdentifier);
+			preamble.append('.');
+			preamble.append(partIdentifier);
+			preamble.append(": "); //$NON-NLS-1$
+			logPreamble = preamble.toString();
+		}
+		return logPreamble;
+	}
+}

Copied: tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/TestQueryExecutionImpl.java (from rev 2707, branches/7.2.x/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/TestQueryExecutionImpl.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/TestQueryExecutionImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/TestQueryExecutionImpl.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,69 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.salesforce.execution;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.cdk.api.TranslationUtility;
+import org.teiid.language.Select;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.salesforce.SalesforceConnection;
+import org.teiid.translator.salesforce.execution.visitors.TestVisitors;
+import org.w3c.dom.Element;
+
+import com.sforce.soap.partner.QueryResult;
+import com.sforce.soap.partner.sobject.SObject;
+
+ at SuppressWarnings("nls")
+public class TestQueryExecutionImpl {
+	
+	private static TranslationUtility translationUtility = new TranslationUtility(TestVisitors.exampleSalesforce());
+
+	@Test public void testBatching() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("select Name from Account"); //$NON-NLS-1$
+		SalesforceConnection sfc = Mockito.mock(SalesforceConnection.class);
+		QueryResult qr = new QueryResult();
+		SObject so = new SObject();
+		so.setType("Account");
+		Element elem = Mockito.mock(Element.class);
+		Mockito.stub(elem.getLocalName()).toReturn("AccountName");
+		so.getAny().add(elem);
+		qr.getRecords().add(so);
+		qr.setDone(false);
+		QueryResult finalQr = new QueryResult();
+		so.getAny().add(elem);
+		finalQr.getRecords().add(so);
+		finalQr.setDone(true);
+		Mockito.stub(sfc.query("SELECT Account.AccountName FROM Account", 0, false)).toReturn(qr);
+		Mockito.stub(sfc.queryMore(null, 0)).toReturn(finalQr);
+		QueryExecutionImpl qei = new QueryExecutionImpl(command, sfc, Mockito.mock(RuntimeMetadata.class), Mockito.mock(ExecutionContext.class));
+		qei.execute();
+		assertNotNull(qei.next());
+		assertNotNull(qei.next());
+		assertNull(qei.next());
+	}
+	
+}

Deleted: tags/teiid-parent-7.2.0.Final/connectors/translator-ws/pom.xml
===================================================================
--- branches/7.2.x/connectors/translator-ws/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-ws/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,63 +0,0 @@
-<?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">
-    <parent>
-        <artifactId>connectors</artifactId>
-        <groupId>org.jboss.teiid</groupId>
-        <version>7.2.0.Final-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>translator-ws</artifactId>
-    <groupId>org.jboss.teiid.connectors</groupId>
-    <name>Web service Translator</name>
-    <description>This translator provides access to Web Services.</description>
-    <dependencies>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>log4j</groupId>
-            <artifactId>log4j</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>javax.resource</groupId>
-            <artifactId>connector-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-    </dependencies>
-
-    <build>
-        <outputDirectory>target/classes</outputDirectory>
-        <resources>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>true</filtering>
-                <includes>
-                    <include>**/*.xml</include>
-                    <include>**/*.properties</include>
-                </includes>
-            </resource>
-            <resource>
-                <directory>src/main/resources</directory>
-                <filtering>false</filtering>
-                <excludes>
-                    <exclude>**/*.xml</exclude>
-                    <exclude>**/*.properties</exclude>
-                </excludes>
-            </resource>
-        </resources>
-    </build>
-
-</project>

Copied: tags/teiid-parent-7.2.0.Final/connectors/translator-ws/pom.xml (from rev 2708, branches/7.2.x/connectors/translator-ws/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/connectors/translator-ws/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/connectors/translator-ws/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,63 @@
+<?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">
+    <parent>
+        <artifactId>connectors</artifactId>
+        <groupId>org.jboss.teiid</groupId>
+        <version>7.2.0.Final</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>translator-ws</artifactId>
+    <groupId>org.jboss.teiid.connectors</groupId>
+    <name>Web service Translator</name>
+    <description>This translator provides access to Web Services.</description>
+    <dependencies>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.resource</groupId>
+            <artifactId>connector-api</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <outputDirectory>target/classes</outputDirectory>
+        <resources>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>true</filtering>
+                <includes>
+                    <include>**/*.xml</include>
+                    <include>**/*.properties</include>
+                </includes>
+            </resource>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>false</filtering>
+                <excludes>
+                    <exclude>**/*.xml</exclude>
+                    <exclude>**/*.properties</exclude>
+                </excludes>
+            </resource>
+        </resources>
+    </build>
+
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/console/pom.xml
===================================================================
--- branches/7.2.x/console/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/console/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,181 +0,0 @@
-<?xml version="1.0"?>
-<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">
-	<parent>
-		<artifactId>teiid-parent</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>teiid-console</artifactId>
-	<name>Console</name>
-	<description>This project is for the RHQ plugin that supports the TEIID Console </description>
-
-	<properties>
-		<!--
-			<org.jboss.jopr.as4.version>1.2.0.GA</org.jboss.jopr.as4.version>
-		-->
-		<org.jboss.jopr.as5.version>1.2.0.GA</org.jboss.jopr.as5.version>
-		<jopr.jboss.as5.plugin.version>1.4.0.B01</jopr.jboss.as5.plugin.version>
-		<org.rhq.version>1.3.0.GA</org.rhq.version>
-		<apache.ant.version>1.7.0</apache.ant.version>
-
-
-	</properties>
-
-	<dependencies>
-		<!--
-			Below are the core modules that are required dependencies of all
-			plugins
-		-->
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-core-domain</artifactId>
-			<version>${org.rhq.version}</version>
-			<scope>provided</scope>
-			<!--
-				provided by the agent/plugin-container
-			-->
-		</dependency>
-
-
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-core-plugin-api</artifactId>
-			<version>${org.rhq.version}</version>
-			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
-		</dependency>
-
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-core-native-system</artifactId>
-			<version>${org.rhq.version}</version>
-			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
-		</dependency>
-
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-jmx-plugin</artifactId>
-			<version>${org.rhq.version}</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-core-util</artifactId>
-			<version>${org.rhq.version}</version>
-		</dependency>
-
-		<dependency>
-			<groupId>mc4j</groupId>
-			<artifactId>org-mc4j-ems</artifactId>
-			<version>1.2.6</version>
-		</dependency>
-
-		<!--
-			TODO: This is a fix for the Javac bug requiring annotations to be
-			available when compiling dependent classes. It is fixed in JDK 6.
-		-->
-		<dependency>
-			<groupId>javax.persistence</groupId>
-			<artifactId>persistence-api</artifactId>
-			<version>1.0</version>
-			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
-		</dependency>
-
-
-		<!--
-			TODO: This is a fix for the Javac bug requiring annotations to be
-			available when compiling dependent classes; it is fixed in JDK 6.
-		-->
-		<dependency>
-			<groupId>jboss.jboss-embeddable-ejb3</groupId>
-			<artifactId>hibernate-all</artifactId>
-			<version>1.0.0.Alpha9</version>
-			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
-		</dependency>
-
-		<dependency>
-			<groupId>commons-logging</groupId>
-			<artifactId>commons-logging</artifactId>
-			<version>1.1</version>
-			<scope>provided</scope>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-			<scope>provided</scope>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-			<type>test-jar</type>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-			<type>test-jar</type>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.jopr</groupId>
-			<artifactId>jopr-embedded-jbas5</artifactId>
-			<type>war</type>
-			<version>${org.jboss.jopr.as5.version}</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.integration</groupId>
-			<artifactId>jboss-profileservice-spi</artifactId>
-			<version>5.1.0.CR2</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.on</groupId>
-			<artifactId>jopr-jboss-as-5-plugin</artifactId>
-			<version>${jopr.jboss.as5.plugin.version}</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.apache.ant</groupId>
-			<artifactId>ant</artifactId>
-		</dependency>
-
-		<dependency>
-			<groupId>org.apache.commons</groupId>
-			<artifactId>commons-io</artifactId>
-			<version>1.3.2</version>
-		</dependency>
-
-
-
-	</dependencies>
-
-	<build>
-		<outputDirectory>target/classes</outputDirectory>
-		<resources>
-			<resource>
-				<directory>src/main/resources</directory>
-				<filtering>true</filtering>
-				<includes>
-					<include>**/*.xml</include>
-					<include>**/*.properties</include>
-				</includes>
-			</resource>
-			<resource>
-				<directory>src/main/resources</directory>
-				<filtering>false</filtering>
-				<excludes>
-					<exclude>**/*.xml</exclude>
-					<exclude>**/*.properties</exclude>
-				</excludes>
-			</resource>
-		</resources>
-	</build>
-
-
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/console/pom.xml (from rev 2708, branches/7.2.x/console/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/console/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/console/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,181 @@
+<?xml version="1.0"?>
+<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">
+	<parent>
+		<artifactId>teiid-parent</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>teiid-console</artifactId>
+	<name>Console</name>
+	<description>This project is for the RHQ plugin that supports the TEIID Console </description>
+
+	<properties>
+		<!--
+			<org.jboss.jopr.as4.version>1.2.0.GA</org.jboss.jopr.as4.version>
+		-->
+		<org.jboss.jopr.as5.version>1.2.0.GA</org.jboss.jopr.as5.version>
+		<jopr.jboss.as5.plugin.version>1.4.0.B01</jopr.jboss.as5.plugin.version>
+		<org.rhq.version>1.3.0.GA</org.rhq.version>
+		<apache.ant.version>1.7.0</apache.ant.version>
+
+
+	</properties>
+
+	<dependencies>
+		<!--
+			Below are the core modules that are required dependencies of all
+			plugins
+		-->
+		<dependency>
+			<groupId>org.rhq</groupId>
+			<artifactId>rhq-core-domain</artifactId>
+			<version>${org.rhq.version}</version>
+			<scope>provided</scope>
+			<!--
+				provided by the agent/plugin-container
+			-->
+		</dependency>
+
+
+		<dependency>
+			<groupId>org.rhq</groupId>
+			<artifactId>rhq-core-plugin-api</artifactId>
+			<version>${org.rhq.version}</version>
+			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
+		</dependency>
+
+		<dependency>
+			<groupId>org.rhq</groupId>
+			<artifactId>rhq-core-native-system</artifactId>
+			<version>${org.rhq.version}</version>
+			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
+		</dependency>
+
+		<dependency>
+			<groupId>org.rhq</groupId>
+			<artifactId>rhq-jmx-plugin</artifactId>
+			<version>${org.rhq.version}</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.rhq</groupId>
+			<artifactId>rhq-core-util</artifactId>
+			<version>${org.rhq.version}</version>
+		</dependency>
+
+		<dependency>
+			<groupId>mc4j</groupId>
+			<artifactId>org-mc4j-ems</artifactId>
+			<version>1.2.6</version>
+		</dependency>
+
+		<!--
+			TODO: This is a fix for the Javac bug requiring annotations to be
+			available when compiling dependent classes. It is fixed in JDK 6.
+		-->
+		<dependency>
+			<groupId>javax.persistence</groupId>
+			<artifactId>persistence-api</artifactId>
+			<version>1.0</version>
+			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
+		</dependency>
+
+
+		<!--
+			TODO: This is a fix for the Javac bug requiring annotations to be
+			available when compiling dependent classes; it is fixed in JDK 6.
+		-->
+		<dependency>
+			<groupId>jboss.jboss-embeddable-ejb3</groupId>
+			<artifactId>hibernate-all</artifactId>
+			<version>1.0.0.Alpha9</version>
+			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
+		</dependency>
+
+		<dependency>
+			<groupId>commons-logging</groupId>
+			<artifactId>commons-logging</artifactId>
+			<version>1.1</version>
+			<scope>provided</scope>
+		</dependency>
+
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-client</artifactId>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-client</artifactId>
+			<type>test-jar</type>
+		</dependency>
+
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-common-core</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-common-core</artifactId>
+			<type>test-jar</type>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.jopr</groupId>
+			<artifactId>jopr-embedded-jbas5</artifactId>
+			<type>war</type>
+			<version>${org.jboss.jopr.as5.version}</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.jboss.integration</groupId>
+			<artifactId>jboss-profileservice-spi</artifactId>
+			<version>5.1.0.CR2</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.jboss.on</groupId>
+			<artifactId>jopr-jboss-as-5-plugin</artifactId>
+			<version>${jopr.jboss.as5.plugin.version}</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.apache.ant</groupId>
+			<artifactId>ant</artifactId>
+		</dependency>
+
+		<dependency>
+			<groupId>org.apache.commons</groupId>
+			<artifactId>commons-io</artifactId>
+			<version>1.3.2</version>
+		</dependency>
+
+
+
+	</dependencies>
+
+	<build>
+		<outputDirectory>target/classes</outputDirectory>
+		<resources>
+			<resource>
+				<directory>src/main/resources</directory>
+				<filtering>true</filtering>
+				<includes>
+					<include>**/*.xml</include>
+					<include>**/*.properties</include>
+				</includes>
+			</resource>
+			<resource>
+				<directory>src/main/resources</directory>
+				<filtering>false</filtering>
+				<excludes>
+					<exclude>**/*.xml</exclude>
+					<exclude>**/*.properties</exclude>
+				</excludes>
+			</resource>
+		</resources>
+	</build>
+
+
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java
===================================================================
--- branches/7.2.x/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,887 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.admin;
-
-import java.lang.reflect.Method;
-import java.net.URL;
-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 javax.naming.NamingException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedOperation;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.managed.plugins.ManagedObjectImpl;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.values.CollectionValueSupport;
-import org.jboss.metatype.api.values.CompositeValueSupport;
-import org.jboss.metatype.api.values.GenericValueSupport;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.MetaValueFactory;
-import org.jboss.metatype.api.values.SimpleValue;
-import org.jboss.metatype.api.values.SimpleValueSupport;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.adminapi.Admin;
-import org.teiid.adminapi.Request;
-import org.teiid.adminapi.Session;
-import org.teiid.adminapi.Transaction;
-import org.teiid.adminapi.VDB.Status;
-import org.teiid.adminapi.impl.RequestMetadata;
-import org.teiid.adminapi.impl.RequestMetadataMapper;
-import org.teiid.rhq.plugin.objects.ExecutedResult;
-import org.teiid.rhq.plugin.util.DeploymentUtils;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform;
-import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.VDB;
-
-public class DQPManagementView implements PluginConstants {
-
-	private static ManagedComponent mc = null;
-	private static final Log LOG = LogFactory
-			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-	private static final MetaValueFactory metaValueFactory = MetaValueFactory
-			.getInstance();
-
-	private static final String VDB_EXT = ".vdb"; //$NON-NLS-1$
-
-	public DQPManagementView() {
-	}
-
-	/*
-	 * Metric methods
-	 */
-	public Object getMetric(ProfileServiceConnection connection,
-			String componentType, String identifier, String metric,
-			Map<String, Object> valueMap) {
-		Object resultObject = new Object();
-
-		if (componentType.equals(PluginConstants.ComponentType.Platform.NAME)) {
-			resultObject = getPlatformMetric(connection, componentType, metric,
-					valueMap);
-		} else if (componentType.equals(PluginConstants.ComponentType.VDB.NAME)) {
-			resultObject = getVdbMetric(connection, componentType, identifier,
-					metric, valueMap);
-		}
-
-		return resultObject;
-	}
-
-	private Object getPlatformMetric(ProfileServiceConnection connection,
-			String componentType, String metric, Map<String, Object> valueMap) {
-
-		Object resultObject = new Object();
-
-		if (metric
-				.equals(PluginConstants.ComponentType.Platform.Metrics.QUERY_COUNT)) {
-			resultObject = new Double(getQueryCount(connection).doubleValue());
-		} else if (metric
-				.equals(PluginConstants.ComponentType.Platform.Metrics.SESSION_COUNT)) {
-			resultObject = new Double(getSessionCount(connection).doubleValue());
-		} else if (metric
-				.equals(PluginConstants.ComponentType.Platform.Metrics.LONG_RUNNING_QUERIES)) {
-			Collection<Request> longRunningQueries = new ArrayList<Request>();
-			getRequestCollectionValue(getLongRunningQueries(connection),
-					longRunningQueries);
-			resultObject = new Double(longRunningQueries.size());
-		} else if (metric
-				.equals(PluginConstants.ComponentType.Platform.Metrics.BUFFER_USAGE)) {
-			try {
-				resultObject = ProfileServiceUtil
-						.doubleValue(getUsedBufferSpace(connection));
-			} catch (Exception e) {
-				final String msg = "Exception executing operation: " + Platform.Operations.GET_BUFFER_USAGE; //$NON-NLS-1$
-				LOG.error(msg, e);
-			}
-		} else if (metric.startsWith(Admin.Cache.PREPARED_PLAN_CACHE.toString()
-				+ ".") //$NON-NLS-1$
-				|| metric.startsWith(Admin.Cache.QUERY_SERVICE_RESULT_SET_CACHE
-						.toString()
-						+ ".")) { //$NON-NLS-1$
-			return getCacheProperty(connection, metric);
-		}
-		return resultObject;
-	}
-
-	private Object getCacheProperty(ProfileServiceConnection connection,
-			String metric) {
-		int dotIndex = metric.indexOf('.');
-		String cacheType = metric.substring(0, dotIndex);
-		String property = metric.substring(dotIndex + 1);
-		CompositeValueSupport mv = (CompositeValueSupport) getCacheStats(
-				connection, cacheType);
-		MetaValue v = mv.get(property);
-		return ((SimpleValue) v).getValue();
-	}
-
-	private Object getVdbMetric(ProfileServiceConnection connection,
-			String componentType, String identifier, String metric,
-			Map<String, Object> valueMap) {
-
-		Object resultObject = new Object();
-
-		if (metric
-				.equals(PluginConstants.ComponentType.VDB.Metrics.ERROR_COUNT)) {
-			// TODO remove version parameter after AdminAPI is changed
-			resultObject = getErrorCount(connection, (String) valueMap
-					.get(VDB.NAME));
-		} else if (metric
-				.equals(PluginConstants.ComponentType.VDB.Metrics.STATUS)) {
-			// TODO remove version parameter after AdminAPI is changed
-			resultObject = getVDBStatus(connection, (String) valueMap
-					.get(VDB.NAME));
-		} else if (metric
-				.equals(PluginConstants.ComponentType.VDB.Metrics.QUERY_COUNT)) {
-			resultObject = new Double(getQueryCount(connection).doubleValue());
-		} else if (metric
-				.equals(PluginConstants.ComponentType.VDB.Metrics.SESSION_COUNT)) {
-			resultObject = new Double(getSessionCount(connection).doubleValue());
-		} else if (metric
-				.equals(PluginConstants.ComponentType.VDB.Metrics.LONG_RUNNING_QUERIES)) {
-			Collection<Request> longRunningQueries = new ArrayList<Request>();
-			getRequestCollectionValue(getLongRunningQueries(connection),
-					longRunningQueries);
-			resultObject = new Double(longRunningQueries.size());
-		}
-		return resultObject;
-	}
-
-	/*
-	 * Operation methods
-	 */
-
-	public void executeOperation(ProfileServiceConnection connection,
-			ExecutedResult operationResult, final Map<String, Object> valueMap) {
-
-		if (operationResult.getComponentType().equals(
-				PluginConstants.ComponentType.Platform.NAME)) {
-			executePlatformOperation(connection, operationResult,
-					operationResult.getOperationName(), valueMap);
-		} else if (operationResult.getComponentType().equals(
-				PluginConstants.ComponentType.VDB.NAME)) {
-			executeVdbOperation(connection, operationResult, operationResult
-					.getOperationName(), valueMap);
-		}
-	}
-
-	private void executePlatformOperation(ProfileServiceConnection connection,
-			ExecutedResult operationResult, final String operationName,
-			final Map<String, Object> valueMap) {
-		Collection<Request> resultObject = new ArrayList<Request>();
-		Collection<Session> activeSessionsCollection = new ArrayList<Session>();
-		Collection<Transaction> transactionsCollection = new ArrayList<Transaction>();
-
-		if (operationName.equals(Platform.Operations.GET_LONGRUNNINGQUERIES)) {
-			List<String> fieldNameList = operationResult.getFieldNameList();
-			getRequestCollectionValue(getLongRunningQueries(connection),
-					resultObject);
-			operationResult.setContent(createReportResultList(fieldNameList,
-					resultObject.iterator()));
-		} else if (operationName.equals(Platform.Operations.GET_SESSIONS)) {
-			List<String> fieldNameList = operationResult.getFieldNameList();
-			MetaValue sessionMetaValue = getSessions(connection);
-			getSessionCollectionValue(sessionMetaValue,
-					activeSessionsCollection);
-			operationResult.setContent(createReportResultList(fieldNameList,
-					activeSessionsCollection.iterator()));
-		} else if (operationName.equals(Platform.Operations.GET_REQUESTS)) {
-			List<String> fieldNameList = operationResult.getFieldNameList();
-			MetaValue requestMetaValue = getRequests(connection);
-			getRequestCollectionValue(requestMetaValue, resultObject);
-			operationResult.setContent(createReportResultList(fieldNameList,
-					resultObject.iterator()));
-		} else if (operationName.equals(Platform.Operations.GET_TRANSACTIONS)) {
-			List<String> fieldNameList = operationResult.getFieldNameList();
-			MetaValue transactionMetaValue = getTransactions(connection);
-			getTransactionCollectionValue(transactionMetaValue,
-					transactionsCollection);
-			operationResult.setContent(createReportResultList(fieldNameList,
-					resultObject.iterator()));
-		} else if (operationName.equals(Platform.Operations.KILL_TRANSACTION)) {
-			Long sessionID = (Long) valueMap
-					.get(Operation.Value.TRANSACTION_ID);
-			MetaValue[] args = new MetaValue[] { metaValueFactory
-					.create(sessionID) };
-			try {
-				executeManagedOperation(connection, getRuntimeEngineDeployer(
-						connection, mc), Platform.Operations.KILL_TRANSACTION,
-						args);
-			} catch (Exception e) {
-				final String msg = "Exception executing operation: " + Platform.Operations.KILL_TRANSACTION; //$NON-NLS-1$
-				LOG.error(msg, e);
-			}
-		} else if (operationName.equals(Platform.Operations.KILL_SESSION)) {
-			Long sessionID = (Long) valueMap.get(Operation.Value.SESSION_ID);
-			MetaValue[] args = new MetaValue[] { metaValueFactory
-					.create(sessionID) };
-			try {
-				executeManagedOperation(connection, getRuntimeEngineDeployer(
-						connection, mc), Platform.Operations.KILL_SESSION, args);
-			} catch (Exception e) {
-				final String msg = "Exception executing operation: " + Platform.Operations.KILL_SESSION; //$NON-NLS-1$
-				LOG.error(msg, e);
-			}
-		} else if (operationName.equals(Platform.Operations.KILL_REQUEST)) {
-			Long requestID = (Long) valueMap.get(Operation.Value.REQUEST_ID);
-			Long sessionID = (Long) valueMap.get(Operation.Value.SESSION_ID);
-			MetaValue[] args = new MetaValue[] {
-					metaValueFactory.create(requestID),
-					metaValueFactory.create(sessionID) };
-			try {
-				executeManagedOperation(connection, getRuntimeEngineDeployer(
-						connection, mc), Platform.Operations.KILL_REQUEST, args);
-			} catch (Exception e) {
-				final String msg = "Exception executing operation: " + Platform.Operations.KILL_REQUEST; //$NON-NLS-1$
-				LOG.error(msg, e);
-			}
-		} else if (operationName.equals(Platform.Operations.DEPLOY_VDB_BY_URL)) {
-			String vdbUrl = (String) valueMap.get(Operation.Value.VDB_URL);
-			String deployName = (String) valueMap
-					.get(Operation.Value.VDB_DEPLOY_NAME);
-			Object vdbVersion = valueMap.get(Operation.Value.VDB_VERSION);
-			// strip off vdb extension if user added it
-			if (deployName.endsWith(VDB_EXT)) {
-				deployName = deployName.substring(0, deployName
-						.lastIndexOf(VDB_EXT));
-			}
-			if (vdbVersion != null) {
-				deployName = deployName
-						+ "." + ((Integer) vdbVersion).toString() + VDB_EXT; //$NON-NLS-1$ 
-			}
-			// add vdb extension if there was no version
-			if (!deployName.endsWith(VDB_EXT)) {
-				deployName = deployName + VDB_EXT;
-			}
-
-			try {
-				URL url = new URL(vdbUrl);
-				DeploymentUtils.deployArchive(deployName, connection
-						.getDeploymentManager(), url, false);
-			} catch (Exception e) {
-				final String msg = "Exception executing operation: " + Platform.Operations.DEPLOY_VDB_BY_URL; //$NON-NLS-1$
-				LOG.error(msg, e);
-				throw new RuntimeException(e);
-			}
-		}
-	}
-
-	private void executeVdbOperation(ProfileServiceConnection connection,
-			ExecutedResult operationResult, final String operationName,
-			final Map<String, Object> valueMap) {
-		Collection<ArrayList<String>> sqlResultsObject = new ArrayList<ArrayList<String>>();
-		Collection<Request> resultObject = new ArrayList<Request>();
-		Collection<Session> activeSessionsCollection = new ArrayList<Session>();
-		String vdbName = (String) valueMap
-				.get(PluginConstants.ComponentType.VDB.NAME);
-		String vdbVersion = (String) valueMap
-				.get(PluginConstants.ComponentType.VDB.VERSION);
-
-		if (operationName.equals(VDB.Operations.GET_PROPERTIES)) {
-			List<String> fieldNameList = operationResult.getFieldNameList();
-			getProperties(connection, PluginConstants.ComponentType.VDB.NAME);
-			operationResult.setContent(createReportResultList(fieldNameList,
-					resultObject.iterator()));
-		} else if (operationName.equals(VDB.Operations.GET_SESSIONS)) {
-			List<String> fieldNameList = operationResult.getFieldNameList();
-			MetaValue sessionMetaValue = getSessions(connection);
-			getSessionCollectionValueForVDB(sessionMetaValue,
-					activeSessionsCollection, vdbName);
-			operationResult.setContent(createReportResultList(fieldNameList,
-					activeSessionsCollection.iterator()));
-		} else if (operationName.equals(VDB.Operations.GET_REQUESTS)) {
-			List<String> fieldNameList = operationResult.getFieldNameList();
-			MetaValue requestMetaValue = getRequestsForVDB(connection, vdbName,
-					Integer.parseInt(vdbVersion));
-			getRequestCollectionValue(requestMetaValue, resultObject);
-			operationResult.setContent(createReportResultList(fieldNameList,
-					resultObject.iterator()));
-		} else if (operationName.equals(VDB.Operations.GET_MATVIEWS)) {
-			List<String> fieldNameList = operationResult.getFieldNameList();
-			MetaValue resultsMetaValue = executeMaterializedViewQuery(
-					connection, formatVdbName(vdbName), Integer
-							.parseInt(vdbVersion));
-			getResultsCollectionValue(resultsMetaValue, sqlResultsObject);
-			operationResult.setContent(createReportResultListForMatViewQuery(
-					fieldNameList, sqlResultsObject.iterator()));
-		} else if (operationName.equals(VDB.Operations.RELOAD_MATVIEW)) {
-			MetaValue resultsMetaValue = reloadMaterializedView(connection,
-					formatVdbName(vdbName), Integer.parseInt(vdbVersion),
-					(String) valueMap.get(Operation.Value.MATVIEW_SCHEMA),
-					(String) valueMap.get(Operation.Value.MATVIEW_TABLE),
-					(Boolean) valueMap.get(Operation.Value.INVALIDATE_MATVIEW));
-			if (resultsMetaValue==null) {
-				operationResult.setContent("failure - see log for details"); //$NON-NLS-1$
-			} else {
-				operationResult.setContent("data successfully refreshed!"); //$NON-NLS-1$
-			}
-		}
-
-	}
-
-	/*
-	 * Helper methods
-	 */
-
-	private String formatVdbName(String vdbName) {
-
-		return vdbName.substring(0, vdbName.indexOf(".")); //$NON-NLS-1$
-	}
-
-	public MetaValue getProperties(ProfileServiceConnection connection,
-			final String component) {
-
-		MetaValue propertyValue = null;
-		MetaValue args = null;
-
-		try {
-			propertyValue = executeManagedOperation(connection,
-					getRuntimeEngineDeployer(connection, mc),
-					PluginConstants.Operation.GET_PROPERTIES, args);
-		} catch (Exception e) {
-			final String msg = "Exception executing operation: " + Platform.Operations.GET_PROPERTIES; //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		return propertyValue;
-
-	}
-
-	protected MetaValue getRequests(ProfileServiceConnection connection) {
-
-		MetaValue requestsCollection = null;
-		MetaValue args = null;
-
-		try {
-			requestsCollection = executeManagedOperation(connection,
-					getRuntimeEngineDeployer(connection, mc),
-
-					PluginConstants.Operation.GET_REQUESTS, args);
-		} catch (Exception e) {
-			final String msg = "Exception executing operation: " + Platform.Operations.GET_REQUESTS; //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		return requestsCollection;
-
-	}
-
-	protected MetaValue executeMaterializedViewQuery(
-			ProfileServiceConnection connection, String vdbName, int vdbVersion) {
-
-		MetaValue resultsCollection = null;
-		MetaValue[] args = new MetaValue[] {
-				MetaValueFactory.getInstance().create(vdbName),
-				MetaValueFactory.getInstance().create(vdbVersion),
-				MetaValueFactory.getInstance().create(
-						Operation.Value.MAT_VIEW_QUERY),
-				MetaValueFactory.getInstance()
-						.create(Long.parseLong("9999999")) }; //$NON-NLS-1$
-
-		try {
-			resultsCollection = executeManagedOperation(connection,
-					getRuntimeEngineDeployer(connection, mc),
-					VDB.Operations.EXECUTE_QUERIES, args);
-		} catch (Exception e) {
-			final String msg = "Exception executing operation: " + VDB.Operations.EXECUTE_QUERIES; //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		return resultsCollection;
-
-	}
-
-	protected MetaValue reloadMaterializedView(
-			ProfileServiceConnection connection, String vdbName,
-			int vdbVersion, String schema, String table, Boolean invalidate) {
-
-		MetaValue result = null;
-		String matView = schema + "." + table; //$NON-NLS-1$
-		String query = PluginConstants.Operation.Value.MAT_VIEW_REFRESH;
-		query = query.replace("param1", matView); //$NON-NLS-1$
-		query = query.replace("param2", invalidate.toString()); //$NON-NLS-1$
-		MetaValue[] args = new MetaValue[] {
-				MetaValueFactory.getInstance().create(vdbName),
-				MetaValueFactory.getInstance().create(vdbVersion),
-				MetaValueFactory.getInstance().create(query),
-				MetaValueFactory.getInstance()
-						.create(Long.parseLong("9999999")) }; //$NON-NLS-1$
-
-		try {
-			result = executeManagedOperation(connection,
-					getRuntimeEngineDeployer(connection, mc),
-					VDB.Operations.EXECUTE_QUERIES, args);
-		} catch (Exception e) {
-			final String msg = "Exception executing operation: " + VDB.Operations.RELOAD_MATVIEW; //$NON-NLS-1$
-			LOG.error(msg, e);
-			
-		}
-
-		return result;
-
-	}
-
-	protected MetaValue getRequestsForVDB(ProfileServiceConnection connection,
-			String vdbName, int vdbVersion) {
-
-		MetaValue requestsCollection = null;
-		MetaValue[] args = new MetaValue[] {
-				MetaValueFactory.getInstance().create(vdbName),
-				MetaValueFactory.getInstance().create(vdbVersion) };
-
-		try {
-			requestsCollection = executeManagedOperation(connection,
-					getRuntimeEngineDeployer(connection, mc),
-					PluginConstants.ComponentType.VDB.Operations.GET_REQUESTS,
-					args);
-		} catch (Exception e) {
-			final String msg = "Exception executing operation: " + Platform.Operations.GET_REQUESTS; //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		return requestsCollection;
-
-	}
-
-	protected MetaValue getTransactions(ProfileServiceConnection connection) {
-
-		MetaValue transactionsCollection = null;
-		MetaValue args = null;
-
-		try {
-			transactionsCollection = executeManagedOperation(connection,
-					getRuntimeEngineDeployer(connection, mc),
-					Platform.Operations.GET_TRANSACTIONS, args);
-		} catch (Exception e) {
-			final String msg = "Exception executing operation: " + Platform.Operations.GET_TRANSACTIONS; //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		return transactionsCollection;
-
-	}
-
-	public MetaValue getSessions(ProfileServiceConnection connection) {
-
-		MetaValue sessionCollection = null;
-		MetaValue args = null;
-
-		try {
-			sessionCollection = executeManagedOperation(connection,
-					getRuntimeEngineDeployer(connection, mc),
-					PluginConstants.Operation.GET_SESSIONS, args);
-		} catch (Exception e) {
-			final String msg = "Exception executing operation: " + Platform.Operations.GET_SESSIONS; //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-		return sessionCollection;
-
-	}
-
-	public static String getVDBStatus(ProfileServiceConnection connection,
-			String vdbName) {
-
-		ManagedComponent mcVdb = null;
-		try {
-			mcVdb = ProfileServiceUtil
-					.getManagedComponent(connection,
-							new org.jboss.managed.api.ComponentType(
-									PluginConstants.ComponentType.VDB.TYPE,
-									PluginConstants.ComponentType.VDB.SUBTYPE),
-							vdbName);
-		} catch (NamingException e) {
-			final String msg = "NamingException in getVDBStatus(): " + e.getExplanation(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		} catch (Exception e) {
-			final String msg = "Exception in getVDBStatus(): " + e.getMessage(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		if (mcVdb == null) {
-			return Status.INACTIVE.toString();
-		}
-
-		return ProfileServiceUtil.getSimpleValue(mcVdb, "status", String.class); //$NON-NLS-1$
-	}
-
-	public static MetaValue executeManagedOperation(
-			ProfileServiceConnection connection, ManagedComponent mc,
-			String operation, MetaValue... args) throws Exception {
-
-		for (ManagedOperation mo : mc.getOperations()) {
-			String opName = mo.getName();
-			if (opName.equals(operation)) {
-				try {
-					if (args.length == 1 && args[0] == null) {
-						return mo.invoke();
-					} else {
-						return mo.invoke(args);
-					}
-				} catch (Exception e) {
-					final String msg = "Exception getting the AdminApi in " + operation; //$NON-NLS-1$
-					LOG.error(msg, e);
-					throw new RuntimeException(e);
-				}
-			}
-		}
-		throw new Exception("No operation found with given name = " + operation); //$NON-NLS-1$
-
-	}
-
-	/**
-	 * @param mc
-	 * @return
-	 */
-	private static ManagedComponent getRuntimeEngineDeployer(
-			ProfileServiceConnection connection, ManagedComponent mc) {
-		try {
-			mc = ProfileServiceUtil.getRuntimeEngineDeployer(connection);
-		} catch (NamingException e) {
-			final String msg = "NamingException getting the DQPManagementView"; //$NON-NLS-1$
-			LOG.error(msg, e);
-		} catch (Exception e1) {
-			final String msg = "Exception getting the DQPManagementView"; //$NON-NLS-1$
-			LOG.error(msg, e1);
-		}
-		return mc;
-	}
-
-	/**
-	 * @param mc
-	 * @return
-	 */
-	private static ManagedComponent getBufferService(
-			ProfileServiceConnection connection, ManagedComponent mc) {
-		try {
-			mc = ProfileServiceUtil.getBufferService(connection);
-		} catch (NamingException e) {
-			final String msg = "NamingException getting the SessionService"; //$NON-NLS-1$
-			LOG.error(msg, e);
-		} catch (Exception e1) {
-			final String msg = "Exception getting the SessionService"; //$NON-NLS-1$
-			LOG.error(msg, e1);
-		}
-		return mc;
-	}
-
-	public static MetaValue getManagedProperty(
-			ProfileServiceConnection connection, ManagedComponent mc,
-			String property) throws Exception {
-
-		ManagedProperty managedProperty = null;
-		try {
-			managedProperty = mc.getProperty(property);
-		} catch (Exception e) {
-			final String msg = "Exception getting the AdminApi in " + property; //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		if (managedProperty != null) {
-			return managedProperty.getValue();
-		}
-
-		throw new Exception("No property found with given name =" + property); //$NON-NLS-1$
-	}
-
-	private Integer getQueryCount(ProfileServiceConnection connection) {
-
-		Integer count = new Integer(0);
-
-		MetaValue requests = null;
-		Collection<Request> requestsCollection = new ArrayList<Request>();
-
-		requests = getRequests(connection);
-
-		getRequestCollectionValue(requests, requestsCollection);
-
-		if (requestsCollection != null && !requestsCollection.isEmpty()) {
-			count = requestsCollection.size();
-		}
-
-		return count;
-	}
-
-	private Integer getSessionCount(ProfileServiceConnection connection) {
-
-		Collection<Session> activeSessionsCollection = new ArrayList<Session>();
-		MetaValue sessionMetaValue = getSessions(connection);
-		getSessionCollectionValue(sessionMetaValue, activeSessionsCollection);
-		return activeSessionsCollection.size();
-	}
-
-	/**
-	 * @param mcVdb
-	 * @return count
-	 * @throws Exception
-	 */
-	private int getErrorCount(ProfileServiceConnection connection,
-			String vdbName) {
-
-		ManagedComponent mcVdb = null;
-		try {
-			mcVdb = ProfileServiceUtil
-					.getManagedComponent(connection,
-							new org.jboss.managed.api.ComponentType(
-									PluginConstants.ComponentType.VDB.TYPE,
-									PluginConstants.ComponentType.VDB.SUBTYPE),
-							vdbName);
-		} catch (NamingException e) {
-			final String msg = "NamingException in getVDBStatus(): " + e.getExplanation(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		} catch (Exception e) {
-			final String msg = "Exception in getVDBStatus(): " + e.getMessage(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		// Get models from VDB
-		int count = 0;
-		ManagedProperty property = mcVdb.getProperty("models"); //$NON-NLS-1$
-		CollectionValueSupport valueSupport = (CollectionValueSupport) property
-				.getValue();
-		MetaValue[] metaValues = valueSupport.getElements();
-
-		for (MetaValue value : metaValues) {
-			GenericValueSupport genValueSupport = (GenericValueSupport) value;
-			ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
-					.getValue();
-
-			// Get any model errors/warnings
-			MetaValue errors = managedObject.getProperty("errors").getValue(); //$NON-NLS-1$
-			if (errors != null) {
-				CollectionValueSupport errorValueSupport = (CollectionValueSupport) errors;
-				MetaValue[] errorArray = errorValueSupport.getElements();
-				count += errorArray.length;
-			}
-		}
-		return count;
-	}
-
-	protected MetaValue getCacheStats(ProfileServiceConnection connection,
-			String type) {
-		try {
-			return executeManagedOperation(connection,
-					getRuntimeEngineDeployer(connection, mc),
-					Platform.Operations.GET_CACHE_STATS, SimpleValueSupport
-							.wrap(type));
-		} catch (Exception e) {
-			LOG
-					.error(
-							"Exception executing operation: " + Platform.Operations.GET_CACHE_STATS, e); //$NON-NLS-1$
-		}
-		return null;
-	}
-
-	protected MetaValue getLongRunningQueries(
-			ProfileServiceConnection connection) {
-
-		MetaValue requestsCollection = null;
-		MetaValue args = null;
-
-		try {
-			requestsCollection = executeManagedOperation(connection,
-					getRuntimeEngineDeployer(connection, mc),
-					Platform.Operations.GET_LONGRUNNINGQUERIES, args);
-		} catch (Exception e) {
-			final String msg = "Exception executing operation: " + Platform.Operations.GET_LONGRUNNINGQUERIES; //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		return requestsCollection;
-	}
-
-	protected MetaValue getUsedBufferSpace(ProfileServiceConnection connection) {
-
-		MetaValue usedBufferSpace = null;
-
-		try {
-			usedBufferSpace = getManagedProperty(connection, getBufferService(
-					connection, mc), Platform.Operations.GET_BUFFER_USAGE);
-		} catch (Exception e) {
-			final String msg = "Exception executing operation: " + Platform.Operations.GET_BUFFER_USAGE; //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		return usedBufferSpace;
-	}
-
-	private void getRequestCollectionValue(MetaValue pValue,
-			Collection<Request> list) {
-		MetaType metaType = pValue.getMetaType();
-		if (metaType.isCollection()) {
-			for (MetaValue value : ((CollectionValueSupport) pValue)
-					.getElements()) {
-				if (value.getMetaType().isComposite()) {
-					RequestMetadataMapper rmm = new RequestMetadataMapper();
-					RequestMetadata request = rmm.unwrapMetaValue(value);
-					list.add(request);
-				} else {
-					throw new IllegalStateException(pValue
-							+ " is not a Composite type"); //$NON-NLS-1$
-				}
-			}
-		}
-	}
-
-	private void getResultsCollectionValue(MetaValue pValue,
-			Collection<ArrayList<String>> list) {
-		MetaType metaType = pValue.getMetaType();
-		if (metaType.isCollection()) {
-			for (MetaValue value : ((CollectionValueSupport) pValue)
-					.getElements()) {
-				if (value.getMetaType().isCollection()) {
-					ArrayList<String> row = (ArrayList<String>) MetaValueFactory
-							.getInstance().unwrap(value);
-					list.add(row);
-				}
-			}
-		}
-	}
-
-	private void getResultsCollectionValueForMatViewRefresh(MetaValue pValue,
-			Collection<ArrayList<String>> list) {
-		MetaType metaType = pValue.getMetaType();
-		for (MetaValue value : ((CollectionValueSupport) pValue).getElements()) {
-			if (value.getMetaType().isCollection()) {
-				ArrayList<String> row = (ArrayList<String>) MetaValueFactory
-						.getInstance().unwrap(value);
-				list.add(row);
-			}
-		}
-
-	}
-
-	public static <T> void getTransactionCollectionValue(MetaValue pValue,
-			Collection<Transaction> list) {
-		MetaType metaType = pValue.getMetaType();
-		if (metaType.isCollection()) {
-			for (MetaValue value : ((CollectionValueSupport) pValue)
-					.getElements()) {
-				if (value.getMetaType().isComposite()) {
-					Transaction transaction = (Transaction) MetaValueFactory
-							.getInstance().unwrap(value);
-					list.add(transaction);
-				} else {
-					throw new IllegalStateException(pValue
-							+ " is not a Composite type"); //$NON-NLS-1$
-				}
-			}
-		}
-	}
-
-	public static <T> void getSessionCollectionValue(MetaValue pValue,
-			Collection<Session> list) {
-		MetaType metaType = pValue.getMetaType();
-		if (metaType.isCollection()) {
-			for (MetaValue value : ((CollectionValueSupport) pValue)
-					.getElements()) {
-				if (value.getMetaType().isComposite()) {
-					Session Session = (Session) MetaValueFactory.getInstance()
-							.unwrap(value);
-					list.add(Session);
-				} else {
-					throw new IllegalStateException(pValue
-							+ " is not a Composite type"); //$NON-NLS-1$
-				}
-			}
-		}
-	}
-
-	public static <T> void getSessionCollectionValueForVDB(MetaValue pValue,
-			Collection<Session> list, String vdbName) {
-		MetaType metaType = pValue.getMetaType();
-		if (metaType.isCollection()) {
-			for (MetaValue value : ((CollectionValueSupport) pValue)
-					.getElements()) {
-				if (value.getMetaType().isComposite()) {
-					Session session = (Session) MetaValueFactory.getInstance()
-							.unwrap(value);
-					if (session.getVDBName().equals(vdbName)) {
-						list.add(session);
-					}
-				} else {
-					throw new IllegalStateException(pValue
-							+ " is not a Composite type"); //$NON-NLS-1$
-				}
-			}
-		}
-	}
-
-	private Collection createReportResultList(List fieldNameList,
-			Iterator objectIter) {
-		Collection reportResultList = new ArrayList();
-
-		while (objectIter.hasNext()) {
-			Object object = objectIter.next();
-
-			Class cls = null;
-			try {
-				cls = object.getClass();
-				Iterator methodIter = fieldNameList.iterator();
-				Map reportValueMap = new HashMap<String, String>();
-				while (methodIter.hasNext()) {
-					String fieldName = (String) methodIter.next();
-					String methodName = fieldName;
-					Method meth = cls.getMethod(methodName, (Class[]) null);
-					Object retObj = meth.invoke(object, (Object[]) null);
-					reportValueMap.put(fieldName, retObj);
-				}
-				reportResultList.add(reportValueMap);
-			} catch (Throwable e) {
-				System.err.println(e);
-			}
-		}
-		return reportResultList;
-	}
-
-	private Collection createReportResultListForMatViewQuery(
-			List fieldNameList, Iterator objectIter) {
-		Collection reportResultList = new ArrayList();
-
-		// Iterate through rows
-		while (objectIter.hasNext()) {
-			ArrayList<Object> columnValues = (ArrayList<Object>) objectIter
-					.next();
-
-			Class cls = null;
-			try {
-				Iterator fieldIter = fieldNameList.iterator();
-				Map reportValueMap = new HashMap<String, Object>();
-				// Iterate through columns with a row
-				for (Object columnValue : columnValues) {
-					String fieldName = (String) fieldIter.next();
-					reportValueMap.put(fieldName, columnValue);
-				}
-				reportResultList.add(reportValueMap);
-			} catch (Throwable e) {
-				System.err.println(e);
-			}
-		}
-		return reportResultList;
-	}
-
-}

Copied: tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java (from rev 2707, branches/7.2.x/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,781 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.admin;
+
+import java.lang.reflect.Method;
+import java.net.URL;
+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 javax.naming.NamingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedOperation;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.plugins.ManagedObjectImpl;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.CollectionValueSupport;
+import org.jboss.metatype.api.values.CompositeValueSupport;
+import org.jboss.metatype.api.values.GenericValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.MetaValueFactory;
+import org.jboss.metatype.api.values.SimpleValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.adminapi.Admin;
+import org.teiid.adminapi.Request;
+import org.teiid.adminapi.Session;
+import org.teiid.adminapi.Transaction;
+import org.teiid.adminapi.VDB.Status;
+import org.teiid.adminapi.impl.RequestMetadata;
+import org.teiid.adminapi.impl.RequestMetadataMapper;
+import org.teiid.rhq.plugin.objects.ExecutedResult;
+import org.teiid.rhq.plugin.util.DeploymentUtils;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform;
+import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.VDB;
+
+public class DQPManagementView implements PluginConstants {
+
+	private static ManagedComponent mc = null;
+	private static final Log LOG = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+	private static final MetaValueFactory metaValueFactory = MetaValueFactory.getInstance();
+
+	private static final String VDB_EXT = ".vdb"; //$NON-NLS-1$
+
+	public DQPManagementView() {
+	}
+
+	/*
+	 * Metric methods
+	 */
+	public Object getMetric(ProfileServiceConnection connection,
+			String componentType, String identifier, String metric,
+			Map<String, Object> valueMap) {
+		Object resultObject = new Object();
+
+		if (componentType.equals(PluginConstants.ComponentType.Platform.NAME)) {
+			resultObject = getPlatformMetric(connection, componentType, metric,	valueMap);
+		} else if (componentType.equals(PluginConstants.ComponentType.VDB.NAME)) {
+			resultObject = getVdbMetric(connection, componentType, identifier,metric, valueMap);
+		}
+		return resultObject;
+	}
+
+	private Object getPlatformMetric(ProfileServiceConnection connection,
+			String componentType, String metric, Map<String, Object> valueMap) {
+
+		Object resultObject = new Object();
+
+		if (metric.equals(PluginConstants.ComponentType.Platform.Metrics.QUERY_COUNT)) {
+			resultObject = new Double(getQueryCount(connection).doubleValue());
+		} else if (metric.equals(PluginConstants.ComponentType.Platform.Metrics.SESSION_COUNT)) {
+			resultObject = new Double(getSessionCount(connection).doubleValue());
+		} else if (metric.equals(PluginConstants.ComponentType.Platform.Metrics.LONG_RUNNING_QUERIES)) {
+			Collection<Request> longRunningQueries = new ArrayList<Request>();
+			getRequestCollectionValue(getLongRunningQueries(connection),	longRunningQueries);
+			resultObject = new Double(longRunningQueries.size());
+		} else if (metric.equals(PluginConstants.ComponentType.Platform.Metrics.BUFFER_USAGE)) {
+			try {
+				resultObject = ProfileServiceUtil.doubleValue(getUsedBufferSpace(connection));
+			} catch (Exception e) {
+				final String msg = "Exception executing operation: " + Platform.Operations.GET_BUFFER_USAGE; //$NON-NLS-1$
+				LOG.error(msg, e);
+			}
+		} else if (metric.startsWith(Admin.Cache.PREPARED_PLAN_CACHE.toString() + ".") //$NON-NLS-1$
+				|| metric.startsWith(Admin.Cache.QUERY_SERVICE_RESULT_SET_CACHE	.toString()+ ".")) { //$NON-NLS-1$
+			return getCacheProperty(connection, metric);
+		}
+		return resultObject;
+	}
+
+	private Object getCacheProperty(ProfileServiceConnection connection,String metric) {
+		int dotIndex = metric.indexOf('.');
+		String cacheType = metric.substring(0, dotIndex);
+		String property = metric.substring(dotIndex + 1);
+		CompositeValueSupport mv = (CompositeValueSupport) getCacheStats(connection, cacheType);
+		MetaValue v = mv.get(property);
+		return ((SimpleValue) v).getValue();
+	}
+
+	private Object getVdbMetric(ProfileServiceConnection connection,
+			String componentType, String identifier, String metric,
+			Map<String, Object> valueMap) {
+
+		Object resultObject = new Object();
+
+		if (metric.equals(PluginConstants.ComponentType.VDB.Metrics.ERROR_COUNT)) {
+			// TODO remove version parameter after AdminAPI is changed
+			resultObject = getErrorCount(connection, (String) valueMap.get(VDB.NAME));
+		} else if (metric.equals(PluginConstants.ComponentType.VDB.Metrics.STATUS)) {
+			// TODO remove version parameter after AdminAPI is changed
+			resultObject = getVDBStatus(connection, (String) valueMap.get(VDB.NAME));
+		} else if (metric.equals(PluginConstants.ComponentType.VDB.Metrics.QUERY_COUNT)) {
+			resultObject = new Double(getQueryCount(connection).doubleValue());
+		} else if (metric.equals(PluginConstants.ComponentType.VDB.Metrics.SESSION_COUNT)) {
+			resultObject = new Double(getSessionCount(connection).doubleValue());
+		} else if (metric.equals(PluginConstants.ComponentType.VDB.Metrics.LONG_RUNNING_QUERIES)) {
+			Collection<Request> longRunningQueries = new ArrayList<Request>();
+			getRequestCollectionValue(getLongRunningQueries(connection),	longRunningQueries);
+			resultObject = new Double(longRunningQueries.size());
+		}
+		return resultObject;
+	}
+
+	/*
+	 * Operation methods
+	 */
+
+	public void executeOperation(ProfileServiceConnection connection,
+			ExecutedResult operationResult, final Map<String, Object> valueMap) {
+
+		if (operationResult.getComponentType().equals(PluginConstants.ComponentType.Platform.NAME)) {
+			executePlatformOperation(connection, operationResult,	operationResult.getOperationName(), valueMap);
+		} else if (operationResult.getComponentType().equals(	PluginConstants.ComponentType.VDB.NAME)) {
+			executeVdbOperation(connection, operationResult, operationResult	.getOperationName(), valueMap);
+		}
+	}
+
+	private void executePlatformOperation(ProfileServiceConnection connection,
+			ExecutedResult operationResult, final String operationName,
+			final Map<String, Object> valueMap) {
+		Collection<Request> resultObject = new ArrayList<Request>();
+		Collection<Session> activeSessionsCollection = new ArrayList<Session>();
+		Collection<Transaction> transactionsCollection = new ArrayList<Transaction>();
+
+		if (operationName.equals(Platform.Operations.GET_LONGRUNNINGQUERIES)) {
+			List<String> fieldNameList = operationResult.getFieldNameList();
+			getRequestCollectionValue(getLongRunningQueries(connection),	resultObject);
+			operationResult.setContent(createReportResultList(fieldNameList,	resultObject.iterator()));
+		} else if (operationName.equals(Platform.Operations.GET_SESSIONS)) {
+			List<String> fieldNameList = operationResult.getFieldNameList();
+			MetaValue sessionMetaValue = getSessions(connection);
+			getSessionCollectionValue(sessionMetaValue,activeSessionsCollection);
+			operationResult.setContent(createReportResultList(fieldNameList,	activeSessionsCollection.iterator()));
+		} else if (operationName.equals(Platform.Operations.GET_REQUESTS)) {
+			List<String> fieldNameList = operationResult.getFieldNameList();
+			MetaValue requestMetaValue = getRequests(connection);
+			getRequestCollectionValue(requestMetaValue, resultObject);
+			operationResult.setContent(createReportResultList(fieldNameList,	resultObject.iterator()));
+		} else if (operationName.equals(Platform.Operations.GET_TRANSACTIONS)) {
+			List<String> fieldNameList = operationResult.getFieldNameList();
+			MetaValue transactionMetaValue = getTransactions(connection);
+			getTransactionCollectionValue(transactionMetaValue,transactionsCollection);
+			operationResult.setContent(createReportResultList(fieldNameList,	resultObject.iterator()));
+		} else if (operationName.equals(Platform.Operations.KILL_TRANSACTION)) {
+			Long sessionID = (Long) valueMap.get(Operation.Value.TRANSACTION_ID);
+			MetaValue[] args = new MetaValue[] { metaValueFactory	.create(sessionID) };
+			try {
+				executeManagedOperation(connection, getRuntimeEngineDeployer(connection, mc), Platform.Operations.KILL_TRANSACTION, args);
+			} catch (Exception e) {
+				final String msg = "Exception executing operation: " + Platform.Operations.KILL_TRANSACTION; //$NON-NLS-1$
+				LOG.error(msg, e);
+			}
+		} else if (operationName.equals(Platform.Operations.KILL_SESSION)) {
+			Long sessionID = (Long) valueMap.get(Operation.Value.SESSION_ID);
+			MetaValue[] args = new MetaValue[] { metaValueFactory	.create(sessionID) };
+			try {
+				executeManagedOperation(connection, getRuntimeEngineDeployer(connection, mc), Platform.Operations.KILL_SESSION, args);
+			} catch (Exception e) {
+				final String msg = "Exception executing operation: " + Platform.Operations.KILL_SESSION; //$NON-NLS-1$
+				LOG.error(msg, e);
+			}
+		} else if (operationName.equals(Platform.Operations.KILL_REQUEST)) {
+			Long requestID = (Long) valueMap.get(Operation.Value.REQUEST_ID);
+			Long sessionID = (Long) valueMap.get(Operation.Value.SESSION_ID);
+			MetaValue[] args = new MetaValue[] {
+					metaValueFactory.create(requestID),
+					metaValueFactory.create(sessionID) };
+			try {
+				executeManagedOperation(connection, getRuntimeEngineDeployer(connection, mc), Platform.Operations.KILL_REQUEST, args);
+			} catch (Exception e) {
+				final String msg = "Exception executing operation: " + Platform.Operations.KILL_REQUEST; //$NON-NLS-1$
+				LOG.error(msg, e);
+			}
+		} else if (operationName.equals(Platform.Operations.DEPLOY_VDB_BY_URL)) {
+			String vdbUrl = (String) valueMap.get(Operation.Value.VDB_URL);
+			String deployName = (String) valueMap.get(Operation.Value.VDB_DEPLOY_NAME);
+			Object vdbVersion = valueMap.get(Operation.Value.VDB_VERSION);
+			// strip off vdb extension if user added it
+			if (deployName.endsWith(VDB_EXT)) {
+				deployName = deployName.substring(0, deployName.lastIndexOf(VDB_EXT));
+			}
+			if (vdbVersion != null) {
+				deployName = deployName + "." + ((Integer) vdbVersion).toString() + VDB_EXT; //$NON-NLS-1$ 
+			}
+			// add vdb extension if there was no version
+			if (!deployName.endsWith(VDB_EXT)) {
+				deployName = deployName + VDB_EXT;
+			}
+
+			try {
+				URL url = new URL(vdbUrl);
+				DeploymentUtils.deployArchive(deployName, connection.getDeploymentManager(), url, false);
+			} catch (Exception e) {
+				final String msg = "Exception executing operation: " + Platform.Operations.DEPLOY_VDB_BY_URL; //$NON-NLS-1$
+				LOG.error(msg, e);
+				throw new RuntimeException(e);
+			}
+		}
+	}
+
+	private void executeVdbOperation(ProfileServiceConnection connection,
+			ExecutedResult operationResult, final String operationName,
+			final Map<String, Object> valueMap) {
+		Collection<ArrayList<String>> sqlResultsObject = new ArrayList<ArrayList<String>>();
+		Collection<Request> resultObject = new ArrayList<Request>();
+		Collection<Session> activeSessionsCollection = new ArrayList<Session>();
+		String vdbName = (String) valueMap.get(PluginConstants.ComponentType.VDB.NAME);
+		String vdbVersion = (String) valueMap.get(PluginConstants.ComponentType.VDB.VERSION);
+
+		if (operationName.equals(VDB.Operations.GET_PROPERTIES)) {
+			List<String> fieldNameList = operationResult.getFieldNameList();
+			getProperties(connection, PluginConstants.ComponentType.VDB.NAME);
+			operationResult.setContent(createReportResultList(fieldNameList,	resultObject.iterator()));
+		} else if (operationName.equals(VDB.Operations.GET_SESSIONS)) {
+			List<String> fieldNameList = operationResult.getFieldNameList();
+			MetaValue sessionMetaValue = getSessions(connection);
+			getSessionCollectionValueForVDB(sessionMetaValue, activeSessionsCollection, vdbName);
+			operationResult.setContent(createReportResultList(fieldNameList,	activeSessionsCollection.iterator()));
+		} else if (operationName.equals(VDB.Operations.GET_REQUESTS)) {
+			List<String> fieldNameList = operationResult.getFieldNameList();
+			MetaValue requestMetaValue = getRequestsForVDB(connection, vdbName,	Integer.parseInt(vdbVersion));
+			getRequestCollectionValue(requestMetaValue, resultObject);
+			operationResult.setContent(createReportResultList(fieldNameList,	resultObject.iterator()));
+		} else if (operationName.equals(VDB.Operations.GET_MATVIEWS)) {
+			List<String> fieldNameList = operationResult.getFieldNameList();
+			MetaValue resultsMetaValue = executeMaterializedViewQuery(	connection, formatVdbName(vdbName), Integer.parseInt(vdbVersion));
+			getResultsCollectionValue(resultsMetaValue, sqlResultsObject);
+			operationResult.setContent(createReportResultListForMatViewQuery(fieldNameList, sqlResultsObject.iterator()));
+		} else if (operationName.equals(VDB.Operations.RELOAD_MATVIEW)) {
+			MetaValue resultsMetaValue = reloadMaterializedView(connection,	formatVdbName(vdbName), Integer.parseInt(vdbVersion),
+					(String) valueMap.get(Operation.Value.MATVIEW_SCHEMA),
+					(String) valueMap.get(Operation.Value.MATVIEW_TABLE),
+					(Boolean) valueMap.get(Operation.Value.INVALIDATE_MATVIEW));
+			if (resultsMetaValue==null) {
+				operationResult.setContent("failure - see log for details"); //$NON-NLS-1$
+			} else {
+				operationResult.setContent("data successfully refreshed!"); //$NON-NLS-1$
+			}
+		}
+
+	}
+
+	/*
+	 * Helper methods
+	 */
+
+	private String formatVdbName(String vdbName) {
+
+		return vdbName.substring(0, vdbName.indexOf(".")); //$NON-NLS-1$
+	}
+
+	public MetaValue getProperties(ProfileServiceConnection connection,	final String component) {
+
+		MetaValue propertyValue = null;
+		MetaValue args = null;
+
+		try {
+			propertyValue = executeManagedOperation(connection,	getRuntimeEngineDeployer(connection, mc),
+					PluginConstants.Operation.GET_PROPERTIES, args);
+		} catch (Exception e) {
+			final String msg = "Exception executing operation: " + Platform.Operations.GET_PROPERTIES; //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		return propertyValue;
+
+	}
+
+	protected MetaValue getRequests(ProfileServiceConnection connection) {
+
+		MetaValue requestsCollection = null;
+		MetaValue args = null;
+
+		try {
+			requestsCollection = executeManagedOperation(connection,	getRuntimeEngineDeployer(connection, mc),	PluginConstants.Operation.GET_REQUESTS, args);
+		} catch (Exception e) {
+			final String msg = "Exception executing operation: " + Platform.Operations.GET_REQUESTS; //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		return requestsCollection;
+
+	}
+
+	protected MetaValue executeMaterializedViewQuery(
+			ProfileServiceConnection connection, String vdbName, int vdbVersion) {
+
+		MetaValue resultsCollection = null;
+		MetaValue[] args = new MetaValue[] {
+				MetaValueFactory.getInstance().create(vdbName),
+				MetaValueFactory.getInstance().create(vdbVersion),
+				MetaValueFactory.getInstance().create(Operation.Value.MAT_VIEW_QUERY),	
+				MetaValueFactory.getInstance().create(Long.parseLong("9999999")) }; //$NON-NLS-1$
+
+		try {
+			resultsCollection = executeManagedOperation(connection,	getRuntimeEngineDeployer(connection, mc),	VDB.Operations.EXECUTE_QUERIES, args);
+		} catch (Exception e) {
+			final String msg = "Exception executing operation: " + VDB.Operations.EXECUTE_QUERIES; //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		return resultsCollection;
+
+	}
+
+	protected MetaValue reloadMaterializedView(
+			ProfileServiceConnection connection, String vdbName,
+			int vdbVersion, String schema, String table, Boolean invalidate) {
+
+		MetaValue result = null;
+		String matView = schema + "." + table; //$NON-NLS-1$
+		String query = PluginConstants.Operation.Value.MAT_VIEW_REFRESH;
+		query = query.replace("param1", matView); //$NON-NLS-1$
+		query = query.replace("param2", invalidate.toString()); //$NON-NLS-1$
+		MetaValue[] args = new MetaValue[] {
+				MetaValueFactory.getInstance().create(vdbName),
+				MetaValueFactory.getInstance().create(vdbVersion),
+				MetaValueFactory.getInstance().create(query),
+				MetaValueFactory.getInstance().create(Long.parseLong("9999999")) }; //$NON-NLS-1$
+
+		try {
+			result = executeManagedOperation(connection,	getRuntimeEngineDeployer(connection, mc),
+					VDB.Operations.EXECUTE_QUERIES, args);
+		} catch (Exception e) {
+			final String msg = "Exception executing operation: " + VDB.Operations.RELOAD_MATVIEW; //$NON-NLS-1$
+			LOG.error(msg, e);
+			
+		}
+
+		return result;
+
+	}
+
+	protected MetaValue getRequestsForVDB(ProfileServiceConnection connection,
+			String vdbName, int vdbVersion) {
+
+		MetaValue requestsCollection = null;
+		MetaValue[] args = new MetaValue[] {
+				MetaValueFactory.getInstance().create(vdbName),
+				MetaValueFactory.getInstance().create(vdbVersion) };
+
+		try {
+			requestsCollection = executeManagedOperation(connection,
+					getRuntimeEngineDeployer(connection, mc),
+					PluginConstants.ComponentType.VDB.Operations.GET_REQUESTS,
+					args);
+		} catch (Exception e) {
+			final String msg = "Exception executing operation: " + Platform.Operations.GET_REQUESTS; //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		return requestsCollection;
+
+	}
+
+	protected MetaValue getTransactions(ProfileServiceConnection connection) {
+
+		MetaValue transactionsCollection = null;
+		MetaValue args = null;
+
+		try {
+			transactionsCollection = executeManagedOperation(connection,
+					getRuntimeEngineDeployer(connection, mc),
+					Platform.Operations.GET_TRANSACTIONS, args);
+		} catch (Exception e) {
+			final String msg = "Exception executing operation: " + Platform.Operations.GET_TRANSACTIONS; //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		return transactionsCollection;
+
+	}
+
+	public MetaValue getSessions(ProfileServiceConnection connection) {
+
+		MetaValue sessionCollection = null;
+		MetaValue args = null;
+
+		try {
+			sessionCollection = executeManagedOperation(connection,
+					getRuntimeEngineDeployer(connection, mc),
+					PluginConstants.Operation.GET_SESSIONS, args);
+		} catch (Exception e) {
+			final String msg = "Exception executing operation: " + Platform.Operations.GET_SESSIONS; //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+		return sessionCollection;
+
+	}
+
+	public static String getVDBStatus(ProfileServiceConnection connection,
+			String vdbName) {
+
+		ManagedComponent mcVdb = null;
+		try {
+			mcVdb = ProfileServiceUtil.getManagedComponent(connection,
+							new org.jboss.managed.api.ComponentType(
+									PluginConstants.ComponentType.VDB.TYPE,
+									PluginConstants.ComponentType.VDB.SUBTYPE),	vdbName);
+		} catch (NamingException e) {
+			final String msg = "NamingException in getVDBStatus(): " + e.getExplanation(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		} catch (Exception e) {
+			final String msg = "Exception in getVDBStatus(): " + e.getMessage(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		if (mcVdb == null) {
+			return Status.INACTIVE.toString();
+		}
+
+		return ProfileServiceUtil.getSimpleValue(mcVdb, "status", String.class); //$NON-NLS-1$
+	}
+
+	public static MetaValue executeManagedOperation(
+			ProfileServiceConnection connection, ManagedComponent mc,
+			String operation, MetaValue... args) throws Exception {
+
+		for (ManagedOperation mo : mc.getOperations()) {
+			String opName = mo.getName();
+			if (opName.equals(operation)) {
+				try {
+					if (args.length == 1 && args[0] == null) {
+						return mo.invoke();
+					}
+					return mo.invoke(args);
+				} catch (Exception e) {
+					final String msg = "Exception getting the AdminApi in " + operation; //$NON-NLS-1$
+					LOG.error(msg, e);
+					throw new RuntimeException(e);
+				}
+			}
+		}
+		throw new Exception("No operation found with given name = " + operation); //$NON-NLS-1$
+
+	}
+
+	/**
+	 * @param mc
+	 * @return
+	 */
+	private static ManagedComponent getRuntimeEngineDeployer(
+			ProfileServiceConnection connection, ManagedComponent mc) {
+		try {
+			mc = ProfileServiceUtil.getRuntimeEngineDeployer(connection);
+		} catch (NamingException e) {
+			final String msg = "NamingException getting the DQPManagementView"; //$NON-NLS-1$
+			LOG.error(msg, e);
+		} catch (Exception e1) {
+			final String msg = "Exception getting the DQPManagementView"; //$NON-NLS-1$
+			LOG.error(msg, e1);
+		}
+		return mc;
+	}
+
+	/**
+	 * @param mc
+	 * @return
+	 */
+	private static ManagedComponent getBufferService(ProfileServiceConnection connection, ManagedComponent mc) {
+		try {
+			mc = ProfileServiceUtil.getBufferService(connection);
+		} catch (NamingException e) {
+			final String msg = "NamingException getting the SessionService"; //$NON-NLS-1$
+			LOG.error(msg, e);
+		} catch (Exception e1) {
+			final String msg = "Exception getting the SessionService"; //$NON-NLS-1$
+			LOG.error(msg, e1);
+		}
+		return mc;
+	}
+
+	public static MetaValue getManagedProperty(ProfileServiceConnection connection, ManagedComponent mc, String property) throws Exception {
+
+		ManagedProperty managedProperty = null;
+		try {
+			managedProperty = mc.getProperty(property);
+		} catch (Exception e) {
+			final String msg = "Exception getting the AdminApi in " + property; //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		if (managedProperty != null) {
+			return managedProperty.getValue();
+		}
+
+		throw new Exception("No property found with given name =" + property); //$NON-NLS-1$
+	}
+
+	private Integer getQueryCount(ProfileServiceConnection connection) {
+
+		Integer count = new Integer(0);
+
+		MetaValue requests = null;
+		Collection<Request> requestsCollection = new ArrayList<Request>();
+
+		requests = getRequests(connection);
+
+		getRequestCollectionValue(requests, requestsCollection);
+
+		if (!requestsCollection.isEmpty()) {
+			count = requestsCollection.size();
+		}
+
+		return count;
+	}
+
+	private Integer getSessionCount(ProfileServiceConnection connection) {
+
+		Collection<Session> activeSessionsCollection = new ArrayList<Session>();
+		MetaValue sessionMetaValue = getSessions(connection);
+		getSessionCollectionValue(sessionMetaValue, activeSessionsCollection);
+		return activeSessionsCollection.size();
+	}
+
+	/**
+	 * @param mcVdb
+	 * @return count
+	 * @throws Exception
+	 */
+	private int getErrorCount(ProfileServiceConnection connection,String vdbName) {
+
+		ManagedComponent mcVdb = null;
+		try {
+			mcVdb = ProfileServiceUtil.getManagedComponent(connection,
+							new org.jboss.managed.api.ComponentType(
+									PluginConstants.ComponentType.VDB.TYPE,
+									PluginConstants.ComponentType.VDB.SUBTYPE),vdbName);
+		} catch (NamingException e) {
+			final String msg = "NamingException in getVDBStatus(): " + e.getExplanation(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		} catch (Exception e) {
+			final String msg = "Exception in getVDBStatus(): " + e.getMessage(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		// Get models from VDB
+		int count = 0;
+		ManagedProperty property = mcVdb.getProperty("models"); //$NON-NLS-1$
+		CollectionValueSupport valueSupport = (CollectionValueSupport) property.getValue();
+		MetaValue[] metaValues = valueSupport.getElements();
+
+		for (MetaValue value : metaValues) {
+			GenericValueSupport genValueSupport = (GenericValueSupport) value;
+			ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport.getValue();
+
+			// Get any model errors/warnings
+			MetaValue errors = managedObject.getProperty("errors").getValue(); //$NON-NLS-1$
+			if (errors != null) {
+				CollectionValueSupport errorValueSupport = (CollectionValueSupport) errors;
+				MetaValue[] errorArray = errorValueSupport.getElements();
+				count += errorArray.length;
+			}
+		}
+		return count;
+	}
+
+	protected MetaValue getCacheStats(ProfileServiceConnection connection,
+			String type) {
+		try {
+			return executeManagedOperation(connection,getRuntimeEngineDeployer(connection, mc),
+					Platform.Operations.GET_CACHE_STATS, SimpleValueSupport.wrap(type));
+		} catch (Exception e) {
+			LOG.error("Exception executing operation: " + Platform.Operations.GET_CACHE_STATS, e); //$NON-NLS-1$
+		}
+		return null;
+	}
+
+	protected MetaValue getLongRunningQueries(
+			ProfileServiceConnection connection) {
+
+		MetaValue requestsCollection = null;
+		MetaValue args = null;
+
+		try {
+			requestsCollection = executeManagedOperation(connection,
+					getRuntimeEngineDeployer(connection, mc),
+					Platform.Operations.GET_LONGRUNNINGQUERIES, args);
+		} catch (Exception e) {
+			final String msg = "Exception executing operation: " + Platform.Operations.GET_LONGRUNNINGQUERIES; //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		return requestsCollection;
+	}
+
+	protected MetaValue getUsedBufferSpace(ProfileServiceConnection connection) {
+
+		MetaValue usedBufferSpace = null;
+
+		try {
+			usedBufferSpace = getManagedProperty(connection, getBufferService(
+					connection, mc), Platform.Operations.GET_BUFFER_USAGE);
+		} catch (Exception e) {
+			final String msg = "Exception executing operation: " + Platform.Operations.GET_BUFFER_USAGE; //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		return usedBufferSpace;
+	}
+
+	private void getRequestCollectionValue(MetaValue pValue, Collection<Request> list) {
+		MetaType metaType = pValue.getMetaType();
+		if (metaType.isCollection()) {
+			for (MetaValue value : ((CollectionValueSupport) pValue).getElements()) {
+				if (value.getMetaType().isComposite()) {
+					RequestMetadataMapper rmm = new RequestMetadataMapper();
+					RequestMetadata request = rmm.unwrapMetaValue(value);
+					list.add(request);
+				} else {
+					throw new IllegalStateException(pValue + " is not a Composite type"); //$NON-NLS-1$
+				}
+			}
+		}
+	}
+
+	private void getResultsCollectionValue(MetaValue pValue, Collection<ArrayList<String>> list) {
+		MetaType metaType = pValue.getMetaType();
+		if (metaType.isCollection()) {
+			for (MetaValue value : ((CollectionValueSupport) pValue).getElements()) {
+				if (value.getMetaType().isCollection()) {
+					ArrayList<String> row = (ArrayList<String>) MetaValueFactory.getInstance().unwrap(value);
+					list.add(row);
+				}
+			}
+		}
+	}
+
+	private void getResultsCollectionValueForMatViewRefresh(MetaValue pValue, Collection<ArrayList<String>> list) {
+		MetaType metaType = pValue.getMetaType();
+		for (MetaValue value : ((CollectionValueSupport) pValue).getElements()) {
+			if (value.getMetaType().isCollection()) {
+				ArrayList<String> row = (ArrayList<String>) MetaValueFactory.getInstance().unwrap(value);
+				list.add(row);
+			}
+		}
+	}
+
+	public static <T> void getTransactionCollectionValue(MetaValue pValue, Collection<Transaction> list) {
+		MetaType metaType = pValue.getMetaType();
+		if (metaType.isCollection()) {
+			for (MetaValue value : ((CollectionValueSupport) pValue).getElements()) {
+				if (value.getMetaType().isComposite()) {
+					Transaction transaction = (Transaction) MetaValueFactory.getInstance().unwrap(value);
+					list.add(transaction);
+				} else {
+					throw new IllegalStateException(pValue
+							+ " is not a Composite type"); //$NON-NLS-1$
+				}
+			}
+		}
+	}
+
+	public static <T> void getSessionCollectionValue(MetaValue pValue,Collection<Session> list) {
+		MetaType metaType = pValue.getMetaType();
+		if (metaType.isCollection()) {
+			for (MetaValue value : ((CollectionValueSupport) pValue).getElements()) {
+				if (value.getMetaType().isComposite()) {
+					Session Session = (Session) MetaValueFactory.getInstance().unwrap(value);
+					list.add(Session);
+				} else {
+					throw new IllegalStateException(pValue
+							+ " is not a Composite type"); //$NON-NLS-1$
+				}
+			}
+		}
+	}
+
+	public static <T> void getSessionCollectionValueForVDB(MetaValue pValue,Collection<Session> list, String vdbName) {
+		MetaType metaType = pValue.getMetaType();
+		if (metaType.isCollection()) {
+			for (MetaValue value : ((CollectionValueSupport) pValue).getElements()) {
+				if (value.getMetaType().isComposite()) {
+					Session session = (Session) MetaValueFactory.getInstance().unwrap(value);
+					if (session.getVDBName().equals(vdbName)) {
+						list.add(session);
+					}
+				} else {
+					throw new IllegalStateException(pValue+ " is not a Composite type"); //$NON-NLS-1$
+				}
+			}
+		}
+	}
+
+	private Collection createReportResultList(List fieldNameList, Iterator objectIter) {
+		Collection reportResultList = new ArrayList();
+
+		while (objectIter.hasNext()) {
+			Object object = objectIter.next();
+
+			Class cls = null;
+			try {
+				cls = object.getClass();
+				Iterator methodIter = fieldNameList.iterator();
+				Map reportValueMap = new HashMap<String, String>();
+				while (methodIter.hasNext()) {
+					String fieldName = (String) methodIter.next();
+					String methodName = fieldName;
+					Method meth = cls.getMethod(methodName, (Class[]) null);
+					Object retObj = meth.invoke(object, (Object[]) null);
+					reportValueMap.put(fieldName, retObj);
+				}
+				reportResultList.add(reportValueMap);
+			} catch (Throwable e) {
+				System.err.println(e);
+			}
+		}
+		return reportResultList;
+	}
+
+	private Collection createReportResultListForMatViewQuery(List fieldNameList, Iterator objectIter) {
+		Collection reportResultList = new ArrayList();
+
+		// Iterate through rows
+		while (objectIter.hasNext()) {
+			ArrayList<Object> columnValues = (ArrayList<Object>) objectIter.next();
+
+			try {
+				Iterator fieldIter = fieldNameList.iterator();
+				Map reportValueMap = new HashMap<String, Object>();
+				// Iterate through columns with a row
+				for (Object columnValue : columnValues) {
+					String fieldName = (String) fieldIter.next();
+					reportValueMap.put(fieldName, columnValue);
+				}
+				reportResultList.add(reportValueMap);
+			} catch (Throwable e) {
+				System.err.println(e);
+			}
+		}
+		return reportResultList;
+	}
+
+}

Deleted: tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/Facet.java
===================================================================
--- branches/7.2.x/console/src/main/java/org/teiid/rhq/plugin/Facet.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/Facet.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,884 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.deployers.spi.management.ManagementView;
-import org.jboss.deployers.spi.management.deploy.DeploymentManager;
-import org.jboss.deployers.spi.management.deploy.DeploymentProgress;
-import org.jboss.deployers.spi.management.deploy.DeploymentStatus;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.DeploymentTemplateInfo;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.profileservice.spi.NoSuchDeploymentException;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
-import org.rhq.core.domain.content.PackageDetailsKey;
-import org.rhq.core.domain.content.PackageType;
-import org.rhq.core.domain.content.transfer.ContentResponseResult;
-import org.rhq.core.domain.content.transfer.DeployIndividualPackageResponse;
-import org.rhq.core.domain.content.transfer.DeployPackageStep;
-import org.rhq.core.domain.content.transfer.DeployPackagesResponse;
-import org.rhq.core.domain.content.transfer.RemovePackagesResponse;
-import org.rhq.core.domain.content.transfer.ResourcePackageDetails;
-import org.rhq.core.domain.measurement.AvailabilityType;
-import org.rhq.core.domain.measurement.MeasurementReport;
-import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.core.domain.resource.CreateResourceStatus;
-import org.rhq.core.domain.resource.ResourceType;
-import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
-import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
-import org.rhq.core.pluginapi.content.ContentFacet;
-import org.rhq.core.pluginapi.content.ContentServices;
-import org.rhq.core.pluginapi.content.version.PackageVersions;
-import org.rhq.core.pluginapi.inventory.CreateChildResourceFacet;
-import org.rhq.core.pluginapi.inventory.CreateResourceReport;
-import org.rhq.core.pluginapi.inventory.DeleteResourceFacet;
-import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
-import org.rhq.core.pluginapi.inventory.ResourceComponent;
-import org.rhq.core.pluginapi.inventory.ResourceContext;
-import org.rhq.core.pluginapi.measurement.MeasurementFacet;
-import org.rhq.core.pluginapi.operation.OperationFacet;
-import org.rhq.core.pluginapi.operation.OperationResult;
-import org.rhq.core.util.exception.ThrowableUtil;
-import org.rhq.plugins.jbossas5.ProfileServiceComponent;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.rhq.admin.DQPManagementView;
-import org.teiid.rhq.plugin.objects.ExecutedOperationResultImpl;
-import org.teiid.rhq.plugin.objects.ExecutedResult;
-import org.teiid.rhq.plugin.util.DeploymentUtils;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-
-/**
- * This class implements required RHQ interfaces and provides common logic used
- * by all MetaMatrix components.
- */
-public abstract class Facet implements
-		ProfileServiceComponent<ResourceComponent>, MeasurementFacet,
-		OperationFacet, ConfigurationFacet, ContentFacet, DeleteResourceFacet,
-		CreateChildResourceFacet {
-
-	protected final Log LOG = LogFactory
-			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-	/**
-	 * Represents the resource configuration of the custom product being
-	 * managed.
-	 */
-	protected Configuration resourceConfiguration;
-
-	/**
-	 * All AMPS plugins are stateful - this context contains information that
-	 * your resource component can use when performing its processing.
-	 */
-	protected ResourceContext<?> resourceContext;
-
-	protected String name;
-
-	private String identifier;
-
-	protected String componentType;
-
-	protected boolean isAvailable = false;
-
-	private final Log log = LogFactory.getLog(this.getClass());
-
-	private File deploymentFile;
-	private static final String BACKUP_FILE_EXTENSION = ".rej"; //$NON-NLS-1$
-
-	/**
-	 * The name of the ManagedDeployment (e.g.:
-	 * C:/opt/jboss-5.0.0.GA/server/default/deploy/foo.vdb).
-	 */
-	protected String deploymentName;
-	protected String deploymentUrl;
-
-	private PackageVersions versions = null;
-
-	/**
-	 * Name of the backing package type that will be used when discovering
-	 * packages. This corresponds to the name of the package type defined in the
-	 * plugin descriptor. For simplicity, the package type for VDBs is called
-	 * "vdb". This is still unique within the context of the parent resource
-	 * type and lets this class use the same package type name in both cases.
-	 */
-	private static final String PKG_TYPE_VDB = "vdb"; //$NON-NLS-1$
-
-	/**
-	 * Architecture string used in describing discovered packages.
-	 */
-	private static final String ARCHITECTURE = "noarch"; //$NON-NLS-1$
-
-	abstract String getComponentType();
-
-	/**
-	 * This is called when your component has been started with the given
-	 * context. You normally initialize some internal state of your component as
-	 * well as attempt to make a stateful connection to your managed resource.
-	 * 
-	 * @see ResourceComponent#start(ResourceContext)
-	 */
-	public void start(ResourceContext context) {
-		resourceContext = context;
-		deploymentName = context.getResourceKey();
-	}
-
-	/**
-	 * This is called when the component is being stopped, usually due to the
-	 * plugin container shutting down. You can perform some cleanup here; though
-	 * normally not much needs to be done here.
-	 * 
-	 * @see ResourceComponent#stop()
-	 */
-	public void stop() {
-		this.isAvailable = false;
-	}
-
-	/**
-	 * @return the resourceConfiguration
-	 */
-	public Configuration getResourceConfiguration() {
-		return resourceConfiguration;
-	}
-
-	/**
-	 * @param resourceConfiguration
-	 *            the resourceConfiguration to set
-	 */
-	public void setResourceConfiguration(Configuration resourceConfiguration) {
-		this.resourceConfiguration = resourceConfiguration;
-	}
-
-	public String componentType() {
-		return name;
-	}
-
-	protected void setComponentName(String componentName) {
-		this.name = componentName;
-	}
-
-	public String getComponentIdentifier() {
-		return identifier;
-	}
-
-	protected void setComponentIdentifier(String identifier) {
-		this.identifier = identifier;
-	}
-
-	protected void setOperationArguments(String name,
-			Configuration configuration, Map<String, Object> argumentMap) {
-		// moved this logic up to the associated implemented class
-		throw new InvalidPluginConfigurationException(
-				"Not implemented on component type " + this.getComponentType() //$NON-NLS-1$
-						+ " named " + this.name); //$NON-NLS-1$
-
-	}
-
-	protected void setMetricArguments(String name, Configuration configuration,
-			Map<String, Object> argumentMap) {
-		// moved this logic up to the associated implemented class
-		throw new InvalidPluginConfigurationException(
-				"Not implemented on component type " + this.getComponentType() //$NON-NLS-1$
-						+ " named " + this.name); //$NON-NLS-1$
-
-	}
-
-	protected void execute(final ProfileServiceConnection connection,
-			final ExecutedResult result, final Map<String, Object> valueMap) {
-		DQPManagementView dqp = new DQPManagementView();
-
-		dqp.executeOperation(connection, result, valueMap);
-
-	}
-
-	/*
-	 * (non-Javadoc) This method is called by JON to check the availability of
-	 * the inventoried component on a time scheduled basis
-	 * 
-	 * @see org.rhq.core.pluginapi.inventory.ResourceComponent#getAvailability()
-	 */
-	public AvailabilityType getAvailability() {
-
-		LOG.debug("Checking availability of  " + identifier); //$NON-NLS-1$
-
-		return AvailabilityType.UP;
-	}
-
-	/**
-	 * Helper method that indicates the latest status based on the last
-	 * getAvailabilit() call.
-	 * 
-	 * @return true if the resource is available
-	 */
-	protected boolean isAvailable() {
-		return true;
-	}
-
-	/**
-	 * The plugin container will call this method when your resource component
-	 * has been scheduled to collect some measurements now. It is within this
-	 * method that you actually talk to the managed resource and collect the
-	 * measurement data that is has emitted.
-	 * 
-	 * @see MeasurementFacet#getValues(MeasurementReport, Set)
-	 */
-	public abstract void getValues(MeasurementReport arg0,
-			Set<MeasurementScheduleRequest> arg1) throws Exception;
-
-	/**
-	 * The plugin container will call this method when it wants to invoke an
-	 * operation on your managed resource. Your plugin will connect to the
-	 * managed resource and invoke the analogous operation in your own custom
-	 * way.
-	 * 
-	 * @see OperationFacet#invokeOperation(String, Configuration)
-	 */
-	public OperationResult invokeOperation(String name,
-			Configuration configuration) {
-		Map<String, Object> valueMap = new HashMap<String, Object>();
-
-		Set operationDefinitionSet = this.resourceContext.getResourceType()
-				.getOperationDefinitions();
-
-		ExecutedResult result = new ExecutedOperationResultImpl(this
-				.getComponentType(), name, operationDefinitionSet);
-
-		setOperationArguments(name, configuration, valueMap);
-
-		execute(getConnection(), result, valueMap);
-
-		return ((ExecutedOperationResultImpl) result).getOperationResult();
-
-	}
-
-	/**
-	 * The plugin container will call this method and it needs to obtain the
-	 * current configuration of the managed resource. Your plugin will obtain
-	 * the managed resource's configuration in your own custom way and populate
-	 * the returned Configuration object with the managed resource's
-	 * configuration property values.
-	 * 
-	 * @see ConfigurationFacet#loadResourceConfiguration()
-	 */
-	public Configuration loadResourceConfiguration() {
-		// here we simulate the loading of the managed resource's configuration
-
-		if (resourceConfiguration == null) {
-			// for this example, we will create a simple dummy configuration to
-			// start with.
-			// note that it is empty, so we're assuming there are no required
-			// configs in the plugin descriptor.
-			resourceConfiguration = this.resourceContext
-					.getPluginConfiguration();
-		}
-
-		Configuration config = resourceConfiguration;
-
-		return config;
-	}
-
-	/**
-	 * The plugin container will call this method when it has a new
-	 * configuration for your managed resource. Your plugin will re-configure
-	 * the managed resource in your own custom way, setting its configuration
-	 * based on the new values of the given configuration.
-	 * 
-	 * @see ConfigurationFacet#updateResourceConfiguration(ConfigurationUpdateReport)
-	 */
-	public void updateResourceConfiguration(ConfigurationUpdateReport report) {
-
-		resourceConfiguration = report.getConfiguration().deepCopy();
-
-		Configuration resourceConfig = report.getConfiguration();
-
-		ManagementView managementView = null;
-		ComponentType componentType = null;
-		if (this.getComponentType().equals(
-				PluginConstants.ComponentType.VDB.NAME)) {
-			componentType = new ComponentType(
-					PluginConstants.ComponentType.VDB.TYPE,
-					PluginConstants.ComponentType.VDB.SUBTYPE);
-		} else {
-			report.setStatus(ConfigurationUpdateStatus.FAILURE);
-			report
-					.setErrorMessage("Update not implemented for the component type."); //$NON-NLS-1$
-		}
-
-		ManagedComponent managedComponent = null;
-		report.setStatus(ConfigurationUpdateStatus.SUCCESS);
-		try {
-
-			managementView = getConnection().getManagementView();
-			managedComponent = managementView.getComponent(this.name,
-					componentType);
-			Map<String, ManagedProperty> managedProperties = managedComponent
-					.getProperties();
-
-			ProfileServiceUtil.convertConfigurationToManagedProperties(
-					managedProperties, resourceConfig, resourceContext
-							.getResourceType());
-
-			try {
-				managementView.updateComponent(managedComponent);
-			} catch (Exception e) {
-				LOG.error("Unable to update component [" //$NON-NLS-1$
-						+ managedComponent.getName() + "] of type " //$NON-NLS-1$
-						+ componentType + ".", e); //$NON-NLS-1$
-				report.setStatus(ConfigurationUpdateStatus.FAILURE);
-				report.setErrorMessageFromThrowable(e);
-			}
-		} catch (Exception e) {
-			LOG.error("Unable to process update request", e); //$NON-NLS-1$
-			report.setStatus(ConfigurationUpdateStatus.FAILURE);
-			report.setErrorMessageFromThrowable(e);
-		}
-	}
-
-	/**
-	 * @return
-	 * @throws Exception
-	 */
-	protected Map<String, ManagedProperty> getManagedProperties()
-			throws Exception {
-		return null;
-	}
-
-	/**
-	 * @param managedComponent
-	 * @throws Exception
-	 */
-	protected void updateComponent(ManagedComponent managedComponent)
-			throws Exception {
-		log.trace("Updating " + this.name + " with component " //$NON-NLS-1$ //$NON-NLS-2$
-				+ managedComponent.toString() + "..."); //$NON-NLS-1$
-		ManagementView managementView = getConnection().getManagementView();
-		managementView.updateComponent(managedComponent);
-
-	}
-
-	@Override
-	public void deleteResource() throws Exception {
-
-		DeploymentManager deploymentManager = getConnection()
-				.getDeploymentManager();
-
-		log.debug("Stopping deployment [" + this.deploymentName + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
-		DeploymentProgress progress = deploymentManager
-				.stop(this.deploymentName);
-		DeploymentStatus stopStatus = DeploymentUtils.run(progress);
-		if (stopStatus.isFailed()) {
-			log.error("Failed to stop deployment '" + this.deploymentName //$NON-NLS-1$
-					+ "'.", stopStatus.getFailure()); //$NON-NLS-1$
-			throw new Exception("Failed to stop deployment '" //$NON-NLS-1$
-					+ this.deploymentName + "' - cause: " //$NON-NLS-1$
-					+ stopStatus.getFailure());
-		}
-		log.debug("Removing deployment [" + this.deploymentName + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
-		progress = deploymentManager.remove(this.deploymentName);
-		DeploymentStatus removeStatus = DeploymentUtils.run(progress);
-		if (removeStatus.isFailed()) {
-			log.error("Failed to remove deployment '" + this.deploymentName //$NON-NLS-1$
-					+ "'.", removeStatus.getFailure()); //$NON-NLS-1$
-			throw new Exception("Failed to remove deployment '" //$NON-NLS-1$
-					+ this.deploymentName + "' - cause: " //$NON-NLS-1$
-					+ removeStatus.getFailure());
-		}
-
-	}
-
-	@Override
-	public DeployPackagesResponse deployPackages(
-			Set<ResourcePackageDetails> packages,
-			ContentServices contentServices) {
-		// You can only update the one application file referenced by this
-		// resource, so punch out if multiple are
-		// specified.
-		if (packages.size() != 1) {
-			log
-					.warn("Request to update a VDB file contained multiple packages: " //$NON-NLS-1$
-							+ packages);
-			DeployPackagesResponse response = new DeployPackagesResponse(
-					ContentResponseResult.FAILURE);
-			response
-					.setOverallRequestErrorMessage("When updating a VDB, only one VDB can be updated at a time."); //$NON-NLS-1$
-			return response;
-		}
-
-		ResourcePackageDetails packageDetails = packages.iterator().next();
-
-		log.debug("Updating VDB file '" + this.deploymentFile + "' using [" //$NON-NLS-1$ //$NON-NLS-2$
-				+ packageDetails + "]..."); //$NON-NLS-1$
-
-		log.debug("Writing new VDB bits to temporary file..."); //$NON-NLS-1$
-		File tempFile;
-		try {
-			tempFile = writeNewAppBitsToTempFile(contentServices,
-					packageDetails);
-		} catch (Exception e) {
-			return failApplicationDeployment(
-					"Error writing new application bits to temporary file - cause: " //$NON-NLS-1$
-							+ e, packageDetails);
-		}
-		log.debug("Wrote new VDB bits to temporary file '" + tempFile //$NON-NLS-1$
-				+ "'."); //$NON-NLS-1$
-
-		boolean deployExploded = this.deploymentFile.isDirectory();
-
-		// Backup the original app file/dir to <filename>.rej.
-		File backupOfOriginalFile = new File(this.deploymentFile.getPath()
-				+ BACKUP_FILE_EXTENSION);
-		log.debug("Backing up existing VDB '" + this.deploymentFile //$NON-NLS-1$
-				+ "' to '" + backupOfOriginalFile + "'..."); //$NON-NLS-1$ //$NON-NLS-2$
-		try {
-			if (backupOfOriginalFile.exists())
-				FileUtils.forceDelete(backupOfOriginalFile);
-			if (this.deploymentFile.isDirectory())
-				FileUtils.copyDirectory(this.deploymentFile,
-						backupOfOriginalFile, true);
-			else
-				FileUtils.copyFile(this.deploymentFile, backupOfOriginalFile,
-						true);
-		} catch (Exception e) {
-			throw new RuntimeException("Failed to backup existing EAR/WAR '" //$NON-NLS-1$
-					+ this.deploymentFile + "' to '" + backupOfOriginalFile //$NON-NLS-1$
-					+ "'."); //$NON-NLS-1$
-		}
-
-		// Now stop the original app.
-		try {
-			DeploymentManager deploymentManager = getConnection()
-					.getDeploymentManager();
-			DeploymentProgress progress = deploymentManager
-					.stop(this.deploymentUrl);
-			DeploymentUtils.run(progress);
-		} catch (Exception e) {
-			throw new RuntimeException("Failed to stop deployment [" //$NON-NLS-1$
-					+ this.deploymentUrl + "].", e); //$NON-NLS-1$
-		}
-
-		// And then remove it (this will delete the physical file/dir from the
-		// deploy dir).
-		try {
-			DeploymentManager deploymentManager = getConnection()
-					.getDeploymentManager();
-			DeploymentProgress progress = deploymentManager
-					.remove(this.deploymentUrl);
-			DeploymentUtils.run(progress);
-		} catch (Exception e) {
-			throw new RuntimeException("Failed to remove deployment [" //$NON-NLS-1$
-					+ this.deploymentUrl + "].", e); //$NON-NLS-1$
-		}
-
-		// Deploy away!
-		log.debug("Deploying '" + tempFile + "'..."); //$NON-NLS-1$ //$NON-NLS-2$
-		DeploymentManager deploymentManager = getConnection()
-				.getDeploymentManager();
-		try {
-			DeploymentUtils.deployArchive(deploymentManager, tempFile,
-					deployExploded);
-		} catch (Exception e) {
-			// Deploy failed - rollback to the original app file...
-			log.debug("Redeploy failed - rolling back to original archive...", //$NON-NLS-1$
-					e);
-			String errorMessage = ThrowableUtil.getAllMessages(e);
-			try {
-				// Delete the new app, which failed to deploy.
-				FileUtils.forceDelete(this.deploymentFile);
-				// Need to re-deploy the original file - this generally should
-				// succeed.
-				DeploymentUtils.deployArchive(deploymentManager,
-						backupOfOriginalFile, deployExploded);
-				errorMessage += " ***** ROLLED BACK TO ORIGINAL APPLICATION FILE. *****"; //$NON-NLS-1$
-			} catch (Exception e1) {
-				log.debug("Rollback failed!", e1); //$NON-NLS-1$
-				errorMessage += " ***** FAILED TO ROLLBACK TO ORIGINAL APPLICATION FILE. *****: " //$NON-NLS-1$
-						+ ThrowableUtil.getAllMessages(e1);
-			}
-			log.info("Failed to update VDB file '" + this.deploymentFile //$NON-NLS-1$
-					+ "' using [" + packageDetails + "]."); //$NON-NLS-1$ //$NON-NLS-2$
-			return failApplicationDeployment(errorMessage, packageDetails);
-		}
-
-		// Deploy was successful!
-
-		deleteBackupOfOriginalFile(backupOfOriginalFile);
-		persistApplicationVersion(packageDetails, this.deploymentFile);
-
-		DeployPackagesResponse response = new DeployPackagesResponse(
-				ContentResponseResult.SUCCESS);
-		DeployIndividualPackageResponse packageResponse = new DeployIndividualPackageResponse(
-				packageDetails.getKey(), ContentResponseResult.SUCCESS);
-		response.addPackageResponse(packageResponse);
-
-		log.debug("Updated VDB file '" + this.deploymentFile //$NON-NLS-1$
-				+ "' successfully - returning response [" + response + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
-
-		return response;
-	}
-
-	private void deleteBackupOfOriginalFile(File backupOfOriginalFile) {
-		log.debug("Deleting backup of original file '" + backupOfOriginalFile //$NON-NLS-1$
-				+ "'..."); //$NON-NLS-1$
-		try {
-			FileUtils.forceDelete(backupOfOriginalFile);
-		} catch (Exception e) {
-			// not critical.
-			log.warn("Failed to delete backup of original file: " //$NON-NLS-1$
-					+ backupOfOriginalFile);
-		}
-	}
-	
-	private void persistApplicationVersion(ResourcePackageDetails packageDetails, File appFile)
-    {
-        String packageName = appFile.getName();
-        log.debug("Persisting application version '" + packageDetails.getVersion() + "' for package '" + packageName //$NON-NLS-1$ //$NON-NLS-2$
-                + "'"); //$NON-NLS-1$
-        PackageVersions versions = loadPackageVersions();
-        versions.putVersion(packageName, packageDetails.getVersion());
-    }
-
-	private File writeNewAppBitsToTempFile(ContentServices contentServices,
-			ResourcePackageDetails packageDetails) throws Exception {
-		File tempDir = this.resourceContext.getTemporaryDirectory();
-		File tempFile = new File(tempDir, this.deploymentFile.getName());
-
-		OutputStream tempOutputStream = null;
-		try {
-			tempOutputStream = new BufferedOutputStream(new FileOutputStream(
-					tempFile));
-			long bytesWritten = contentServices.downloadPackageBits(
-					this.resourceContext.getContentContext(), packageDetails
-							.getKey(), tempOutputStream, true);
-			log
-					.debug("Wrote " + bytesWritten + " bytes to '" + tempFile //$NON-NLS-1$ //$NON-NLS-2$
-							+ "'."); //$NON-NLS-1$
-		} catch (IOException e) {
-			log.error(
-					"Error writing updated application bits to temporary location: " //$NON-NLS-1$
-							+ tempFile, e);
-			throw e;
-		} finally {
-			if (tempOutputStream != null) {
-				try {
-					tempOutputStream.close();
-				} catch (IOException e) {
-					log.error("Error closing temporary output stream", e); //$NON-NLS-1$
-				}
-			}
-		}
-		if (!tempFile.exists()) {
-			log.error("Temporary file for application update not written to: " //$NON-NLS-1$
-					+ tempFile);
-			throw new Exception();
-		}
-		return tempFile;
-	}
-
-	/**
-	 * Creates the necessary transfer objects to report a failed application
-	 * deployment (update).
-	 * 
-	 * @param errorMessage
-	 *            reason the deploy failed
-	 * @param packageDetails
-	 *            describes the update being made
-	 * @return response populated to reflect a failure
-	 */
-	private DeployPackagesResponse failApplicationDeployment(
-			String errorMessage, ResourcePackageDetails packageDetails) {
-		DeployPackagesResponse response = new DeployPackagesResponse(
-				ContentResponseResult.FAILURE);
-
-		DeployIndividualPackageResponse packageResponse = new DeployIndividualPackageResponse(
-				packageDetails.getKey(), ContentResponseResult.FAILURE);
-		packageResponse.setErrorMessage(errorMessage);
-
-		response.addPackageResponse(packageResponse);
-
-		return response;
-	}
-
-	@Override
-	public Set<ResourcePackageDetails> discoverDeployedPackages(PackageType arg0) {
-
-		// PLEASE DO NOT REMOVE THIS METHOD. IT IS REQUIRED FOR THE CONTENT TAB.
-
-		Configuration pluginConfig = this.resourceContext
-				.getPluginConfiguration();
-		this.deploymentUrl = pluginConfig.getSimple("url").getStringValue(); //$NON-NLS-1$
-
-		if (this.deploymentUrl != null) {
-			this.deploymentFile = new File(this.deploymentUrl
-					.substring(deploymentUrl.indexOf(":/") + 1)); //$NON-NLS-1$
-		}
-
-		if (!deploymentFile.exists())
-			throw new IllegalStateException("Deployment file '" //$NON-NLS-1$
-					+ this.deploymentFile + "' for " + this.getComponentType() //$NON-NLS-1$
-					+ " does not exist."); //$NON-NLS-1$
-
-		String fileName = deploymentFile.getName();
-		org.rhq.core.pluginapi.content.version.PackageVersions packageVersions = loadPackageVersions();
-		String version = packageVersions.getVersion(fileName);
-		if (version == null) {
-			// This is either the first time we've discovered this VDB, or
-			// someone purged the PC's data dir.
-			version = "1.0"; //$NON-NLS-1$
-			packageVersions.putVersion(fileName, version);
-			packageVersions.saveToDisk();
-		}
-
-		// Package name is the deployment's file name (e.g. foo.ear).
-		PackageDetailsKey key = new PackageDetailsKey(fileName, version,
-				PKG_TYPE_VDB, ARCHITECTURE);
-		ResourcePackageDetails packageDetails = new ResourcePackageDetails(key);
-		packageDetails.setFileName(fileName);
-		packageDetails.setLocation(deploymentFile.getPath());
-		if (!deploymentFile.isDirectory())
-			packageDetails.setFileSize(deploymentFile.length());
-		packageDetails.setFileCreatedDate(null);  
-		Set<ResourcePackageDetails> packages = new HashSet<ResourcePackageDetails>();
-		packages.add(packageDetails);
-
-		return packages;
-	}
-
-	@Override
-	public List<DeployPackageStep> generateInstallationSteps(
-			ResourcePackageDetails arg0) {
-		return null;
-	}
-
-	@Override
-	public RemovePackagesResponse removePackages(
-			Set<ResourcePackageDetails> arg0) {
-		return null;
-	}
-
-	@Override
-	public InputStream retrievePackageBits(ResourcePackageDetails packageDetails) {
-		return null;
-	}
-
-	protected static Configuration getDefaultPluginConfiguration(
-			ResourceType resourceType) {
-		ConfigurationTemplate pluginConfigDefaultTemplate = resourceType
-				.getPluginConfigurationDefinition().getDefaultTemplate();
-		return (pluginConfigDefaultTemplate != null) ? pluginConfigDefaultTemplate
-				.createConfiguration()
-				: new Configuration();
-	}
-
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see
-	 * org.rhq.core.pluginapi.inventory.CreateChildResourceFacet#createResource
-	 * (org.rhq.core.pluginapi.inventory.CreateResourceReport)
-	 */
-	@Override
-	public CreateResourceReport createResource(CreateResourceReport report) {
-		ResourceType resourceType = report.getResourceType();
-		// if (resourceType.getName().equals("Translators")) {
-		// createConfigurationBasedResource(report);
-		// } else {
-		createContentBasedResource(report);
-		// }
-
-		return report;
-	}
-
-	private CreateResourceReport createConfigurationBasedResource(
-			CreateResourceReport createResourceReport) {
-		ResourceType resourceType = createResourceReport.getResourceType();
-		Configuration defaultPluginConfig = getDefaultPluginConfiguration(resourceType);
-		Configuration resourceConfig = createResourceReport
-				.getResourceConfiguration();
-		String resourceName = getResourceName(defaultPluginConfig,
-				resourceConfig);
-		ComponentType componentType = ProfileServiceUtil
-				.getComponentType(resourceType);
-		ManagementView managementView = null;
-		;
-		managementView = getConnection().getManagementView();
-
-		if (ProfileServiceUtil.isManagedComponent(getConnection(),
-				resourceName, componentType)) {
-			createResourceReport.setStatus(CreateResourceStatus.FAILURE);
-			createResourceReport.setErrorMessage("A " + resourceType.getName() //$NON-NLS-1$
-					+ " named '" + resourceName + "' already exists."); //$NON-NLS-1$ //$NON-NLS-2$
-			return createResourceReport;
-		}
-
-		createResourceReport.setResourceName(resourceName);
-		String resourceKey = getResourceKey(resourceType, resourceName);
-		createResourceReport.setResourceKey(resourceKey);
-
-		PropertySimple templateNameProperty = resourceConfig
-				.getSimple(TranslatorComponent.Config.TEMPLATE_NAME);
-		String templateName = templateNameProperty.getStringValue();
-
-		DeploymentTemplateInfo template;
-		try {
-			template = managementView.getTemplate(templateName);
-			Map<String, ManagedProperty> managedProperties = template
-					.getProperties();
-
-			ProfileServiceUtil.convertConfigurationToManagedProperties(
-					managedProperties, resourceConfig, resourceType);
-
-			LOG.debug("Applying template [" + templateName //$NON-NLS-1$
-					+ "] to create ManagedComponent of type [" + componentType //$NON-NLS-1$
-					+ "]..."); //$NON-NLS-1$
-			try {
-				managementView.applyTemplate(resourceName, template);
-				managementView.process();
-				createResourceReport.setStatus(CreateResourceStatus.SUCCESS);
-			} catch (Exception e) {
-				LOG.error("Unable to apply template [" + templateName //$NON-NLS-1$
-						+ "] to create ManagedComponent of type " //$NON-NLS-1$
-						+ componentType + ".", e); //$NON-NLS-1$
-				createResourceReport.setStatus(CreateResourceStatus.FAILURE);
-				createResourceReport.setException(e);
-			}
-		} catch (NoSuchDeploymentException e) {
-			LOG.error("Unable to find template [" + templateName + "].", e); //$NON-NLS-1$ //$NON-NLS-2$
-			createResourceReport.setStatus(CreateResourceStatus.FAILURE);
-			createResourceReport.setException(e);
-		} catch (Exception e) {
-			LOG.error("Unable to process create request", e); //$NON-NLS-1$
-			createResourceReport.setStatus(CreateResourceStatus.FAILURE);
-			createResourceReport.setException(e);
-		}
-		return createResourceReport;
-	}
-
-	protected void createContentBasedResource(
-			CreateResourceReport createResourceReport) {
-
-		ResourcePackageDetails details = createResourceReport
-				.getPackageDetails();
-		PackageDetailsKey key = details.getKey();
-		// This is the full path to a temporary file which was written by the UI
-		// layer.
-		String archivePath = key.getName();
-
-		try {
-			File archiveFile = new File(archivePath);
-
-			if (!DeploymentUtils.hasCorrectExtension(archiveFile.getName(),
-					resourceContext.getResourceType())) {
-				createResourceReport.setStatus(CreateResourceStatus.FAILURE);
-				createResourceReport
-						.setErrorMessage("Incorrect extension specified on filename [" //$NON-NLS-1$
-								+ archivePath + "]"); //$NON-NLS-1$
-
-			}
-
-			DeploymentManager deploymentManager = getConnection()
-					.getDeploymentManager();
-			DeploymentUtils
-					.deployArchive(deploymentManager, archiveFile, false);
-
-			deploymentName = archivePath;
-			createResourceReport.setResourceName(archivePath);
-			createResourceReport.setResourceKey(archivePath);
-			createResourceReport.setStatus(CreateResourceStatus.SUCCESS);
-
-		} catch (Throwable t) {
-			log.error("Error deploying application for report: " //$NON-NLS-1$
-					+ createResourceReport, t);
-			createResourceReport.setStatus(CreateResourceStatus.FAILURE);
-			createResourceReport.setException(t);
-		}
-
-	}
-
-	private static String getResourceName(Configuration pluginConfig,
-			Configuration resourceConfig) {
-		PropertySimple resourceNameProp = pluginConfig
-				.getSimple(TranslatorComponent.Config.RESOURCE_NAME);
-		if (resourceNameProp == null
-				|| resourceNameProp.getStringValue() == null)
-			throw new IllegalStateException("Property [" //$NON-NLS-1$
-					+ TranslatorComponent.Config.RESOURCE_NAME
-					+ "] is not defined in the default plugin configuration."); //$NON-NLS-1$
-		String resourceNamePropName = resourceNameProp.getStringValue();
-		PropertySimple propToUseAsResourceName = resourceConfig
-				.getSimple(resourceNamePropName);
-		if (propToUseAsResourceName == null)
-			throw new IllegalStateException("Property [" + resourceNamePropName //$NON-NLS-1$
-					+ "] is not defined in initial Resource configuration."); //$NON-NLS-1$
-		return propToUseAsResourceName.getStringValue();
-	}
-
-	private String getResourceKey(ResourceType resourceType, String resourceName) {
-		ComponentType componentType = ProfileServiceUtil
-				.getComponentType(resourceType);
-		if (componentType == null)
-			throw new IllegalStateException("Unable to map " + resourceType //$NON-NLS-1$
-					+ " to a ComponentType."); //$NON-NLS-1$
-		return componentType.getType() + ":" + componentType.getSubtype() + ":" //$NON-NLS-1$ //$NON-NLS-2$
-				+ resourceName;
-	}
-
-	/**
-	 * Returns an instantiated and loaded versions store access point.
-	 * 
-	 * @return will not be <code>null</code>
-	 */
-	private org.rhq.core.pluginapi.content.version.PackageVersions loadPackageVersions() {
-		if (this.versions == null) {
-			ResourceType resourceType = resourceContext.getResourceType();
-			String pluginName = resourceType.getPlugin();
-			File dataDirectoryFile = resourceContext.getDataDirectory();
-			dataDirectoryFile.mkdirs();
-			String dataDirectory = dataDirectoryFile.getAbsolutePath();
-			log.trace("Creating application versions store with plugin name [" //$NON-NLS-1$
-					+ pluginName + "] and data directory [" + dataDirectory //$NON-NLS-1$
-					+ "]"); //$NON-NLS-1$
-			this.versions = new PackageVersions(pluginName, dataDirectory);
-			this.versions.loadFromDisk();
-		}
-
-		return this.versions;
-	}
-
-}

Copied: tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/Facet.java (from rev 2707, branches/7.2.x/console/src/main/java/org/teiid/rhq/plugin/Facet.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/Facet.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/Facet.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,880 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.deployers.spi.management.deploy.DeploymentManager;
+import org.jboss.deployers.spi.management.deploy.DeploymentProgress;
+import org.jboss.deployers.spi.management.deploy.DeploymentStatus;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.DeploymentTemplateInfo;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.profileservice.spi.NoSuchDeploymentException;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
+import org.rhq.core.domain.content.PackageDetailsKey;
+import org.rhq.core.domain.content.PackageType;
+import org.rhq.core.domain.content.transfer.ContentResponseResult;
+import org.rhq.core.domain.content.transfer.DeployIndividualPackageResponse;
+import org.rhq.core.domain.content.transfer.DeployPackageStep;
+import org.rhq.core.domain.content.transfer.DeployPackagesResponse;
+import org.rhq.core.domain.content.transfer.RemovePackagesResponse;
+import org.rhq.core.domain.content.transfer.ResourcePackageDetails;
+import org.rhq.core.domain.measurement.AvailabilityType;
+import org.rhq.core.domain.measurement.MeasurementReport;
+import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
+import org.rhq.core.domain.resource.CreateResourceStatus;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
+import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
+import org.rhq.core.pluginapi.content.ContentFacet;
+import org.rhq.core.pluginapi.content.ContentServices;
+import org.rhq.core.pluginapi.content.version.PackageVersions;
+import org.rhq.core.pluginapi.inventory.CreateChildResourceFacet;
+import org.rhq.core.pluginapi.inventory.CreateResourceReport;
+import org.rhq.core.pluginapi.inventory.DeleteResourceFacet;
+import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
+import org.rhq.core.pluginapi.inventory.ResourceComponent;
+import org.rhq.core.pluginapi.inventory.ResourceContext;
+import org.rhq.core.pluginapi.measurement.MeasurementFacet;
+import org.rhq.core.pluginapi.operation.OperationFacet;
+import org.rhq.core.pluginapi.operation.OperationResult;
+import org.rhq.core.util.exception.ThrowableUtil;
+import org.rhq.plugins.jbossas5.ProfileServiceComponent;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.rhq.admin.DQPManagementView;
+import org.teiid.rhq.plugin.objects.ExecutedOperationResultImpl;
+import org.teiid.rhq.plugin.objects.ExecutedResult;
+import org.teiid.rhq.plugin.util.DeploymentUtils;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+
+/**
+ * This class implements required RHQ interfaces and provides common logic used
+ * by all MetaMatrix components.
+ */
+public abstract class Facet implements
+		ProfileServiceComponent<ResourceComponent>, MeasurementFacet,
+		OperationFacet, ConfigurationFacet, ContentFacet, DeleteResourceFacet,
+		CreateChildResourceFacet {
+
+	protected final Log LOG = LogFactory
+			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+	/**
+	 * Represents the resource configuration of the custom product being
+	 * managed.
+	 */
+	protected Configuration resourceConfiguration;
+
+	/**
+	 * All AMPS plugins are stateful - this context contains information that
+	 * your resource component can use when performing its processing.
+	 */
+	protected ResourceContext<?> resourceContext;
+
+	protected String name;
+
+	private String identifier;
+
+	protected String componentType;
+
+	protected boolean isAvailable = false;
+
+	private final Log log = LogFactory.getLog(this.getClass());
+
+	private File deploymentFile;
+	private static final String BACKUP_FILE_EXTENSION = ".rej"; //$NON-NLS-1$
+
+	/**
+	 * The name of the ManagedDeployment (e.g.:
+	 * C:/opt/jboss-5.0.0.GA/server/default/deploy/foo.vdb).
+	 */
+	protected String deploymentName;
+	protected String deploymentUrl;
+
+	private PackageVersions versions = null;
+
+	/**
+	 * Name of the backing package type that will be used when discovering
+	 * packages. This corresponds to the name of the package type defined in the
+	 * plugin descriptor. For simplicity, the package type for VDBs is called
+	 * "vdb". This is still unique within the context of the parent resource
+	 * type and lets this class use the same package type name in both cases.
+	 */
+	private static final String PKG_TYPE_VDB = "vdb"; //$NON-NLS-1$
+
+	/**
+	 * Architecture string used in describing discovered packages.
+	 */
+	private static final String ARCHITECTURE = "noarch"; //$NON-NLS-1$
+
+	abstract String getComponentType();
+
+	/**
+	 * This is called when your component has been started with the given
+	 * context. You normally initialize some internal state of your component as
+	 * well as attempt to make a stateful connection to your managed resource.
+	 * 
+	 * @see ResourceComponent#start(ResourceContext)
+	 */
+	public void start(ResourceContext context) {
+		resourceContext = context;
+		deploymentName = context.getResourceKey();
+	}
+
+	/**
+	 * This is called when the component is being stopped, usually due to the
+	 * plugin container shutting down. You can perform some cleanup here; though
+	 * normally not much needs to be done here.
+	 * 
+	 * @see ResourceComponent#stop()
+	 */
+	public void stop() {
+		this.isAvailable = false;
+	}
+
+	/**
+	 * @return the resourceConfiguration
+	 */
+	public Configuration getResourceConfiguration() {
+		return resourceConfiguration;
+	}
+
+	/**
+	 * @param resourceConfiguration
+	 *            the resourceConfiguration to set
+	 */
+	public void setResourceConfiguration(Configuration resourceConfiguration) {
+		this.resourceConfiguration = resourceConfiguration;
+	}
+
+	public String componentType() {
+		return name;
+	}
+
+	protected void setComponentName(String componentName) {
+		this.name = componentName;
+	}
+
+	public String getComponentIdentifier() {
+		return identifier;
+	}
+
+	protected void setComponentIdentifier(String identifier) {
+		this.identifier = identifier;
+	}
+
+	protected void setOperationArguments(String name,
+			Configuration configuration, Map<String, Object> argumentMap) {
+		// moved this logic up to the associated implemented class
+		throw new InvalidPluginConfigurationException(
+				"Not implemented on component type " + this.getComponentType() //$NON-NLS-1$
+						+ " named " + this.name); //$NON-NLS-1$
+
+	}
+
+	protected void setMetricArguments(String name, Configuration configuration,
+			Map<String, Object> argumentMap) {
+		// moved this logic up to the associated implemented class
+		throw new InvalidPluginConfigurationException(
+				"Not implemented on component type " + this.getComponentType() //$NON-NLS-1$
+						+ " named " + this.name); //$NON-NLS-1$
+
+	}
+
+	protected void execute(final ProfileServiceConnection connection,
+			final ExecutedResult result, final Map<String, Object> valueMap) {
+		DQPManagementView dqp = new DQPManagementView();
+
+		dqp.executeOperation(connection, result, valueMap);
+
+	}
+
+	/*
+	 * (non-Javadoc) This method is called by JON to check the availability of
+	 * the inventoried component on a time scheduled basis
+	 * 
+	 * @see org.rhq.core.pluginapi.inventory.ResourceComponent#getAvailability()
+	 */
+	public AvailabilityType getAvailability() {
+
+		LOG.debug("Checking availability of  " + identifier); //$NON-NLS-1$
+
+		return AvailabilityType.UP;
+	}
+
+	/**
+	 * Helper method that indicates the latest status based on the last
+	 * getAvailabilit() call.
+	 * 
+	 * @return true if the resource is available
+	 */
+	protected boolean isAvailable() {
+		return true;
+	}
+
+	/**
+	 * The plugin container will call this method when your resource component
+	 * has been scheduled to collect some measurements now. It is within this
+	 * method that you actually talk to the managed resource and collect the
+	 * measurement data that is has emitted.
+	 * 
+	 * @see MeasurementFacet#getValues(MeasurementReport, Set)
+	 */
+	public abstract void getValues(MeasurementReport arg0,
+			Set<MeasurementScheduleRequest> arg1) throws Exception;
+
+	/**
+	 * The plugin container will call this method when it wants to invoke an
+	 * operation on your managed resource. Your plugin will connect to the
+	 * managed resource and invoke the analogous operation in your own custom
+	 * way.
+	 * 
+	 * @see OperationFacet#invokeOperation(String, Configuration)
+	 */
+	public OperationResult invokeOperation(String name,
+			Configuration configuration) {
+		Map<String, Object> valueMap = new HashMap<String, Object>();
+
+		Set operationDefinitionSet = this.resourceContext.getResourceType()
+				.getOperationDefinitions();
+
+		ExecutedResult result = new ExecutedOperationResultImpl(this
+				.getComponentType(), name, operationDefinitionSet);
+
+		setOperationArguments(name, configuration, valueMap);
+
+		execute(getConnection(), result, valueMap);
+
+		return ((ExecutedOperationResultImpl) result).getOperationResult();
+
+	}
+
+	/**
+	 * The plugin container will call this method and it needs to obtain the
+	 * current configuration of the managed resource. Your plugin will obtain
+	 * the managed resource's configuration in your own custom way and populate
+	 * the returned Configuration object with the managed resource's
+	 * configuration property values.
+	 * 
+	 * @see ConfigurationFacet#loadResourceConfiguration()
+	 */
+	public Configuration loadResourceConfiguration() {
+		// here we simulate the loading of the managed resource's configuration
+
+		if (resourceConfiguration == null) {
+			// for this example, we will create a simple dummy configuration to
+			// start with.
+			// note that it is empty, so we're assuming there are no required
+			// configs in the plugin descriptor.
+			resourceConfiguration = this.resourceContext
+					.getPluginConfiguration();
+		}
+
+		Configuration config = resourceConfiguration;
+
+		return config;
+	}
+
+	/**
+	 * The plugin container will call this method when it has a new
+	 * configuration for your managed resource. Your plugin will re-configure
+	 * the managed resource in your own custom way, setting its configuration
+	 * based on the new values of the given configuration.
+	 * 
+	 * @see ConfigurationFacet#updateResourceConfiguration(ConfigurationUpdateReport)
+	 */
+	public void updateResourceConfiguration(ConfigurationUpdateReport report) {
+
+		resourceConfiguration = report.getConfiguration().deepCopy();
+
+		Configuration resourceConfig = report.getConfiguration();
+
+		ManagementView managementView = null;
+		ComponentType componentType = null;
+		if (this.getComponentType().equals(
+				PluginConstants.ComponentType.VDB.NAME)) {
+			componentType = new ComponentType(
+					PluginConstants.ComponentType.VDB.TYPE,
+					PluginConstants.ComponentType.VDB.SUBTYPE);
+		} else {
+			report.setStatus(ConfigurationUpdateStatus.FAILURE);
+			report
+					.setErrorMessage("Update not implemented for the component type."); //$NON-NLS-1$
+		}
+
+		ManagedComponent managedComponent = null;
+		report.setStatus(ConfigurationUpdateStatus.SUCCESS);
+		try {
+
+			managementView = getConnection().getManagementView();
+			managedComponent = managementView.getComponent(this.name,
+					componentType);
+			Map<String, ManagedProperty> managedProperties = managedComponent
+					.getProperties();
+
+			ProfileServiceUtil.convertConfigurationToManagedProperties(managedProperties, resourceConfig, resourceContext.getResourceType(), null);
+
+			try {
+				managementView.updateComponent(managedComponent);
+			} catch (Exception e) {
+				LOG.error("Unable to update component [" //$NON-NLS-1$
+						+ managedComponent.getName() + "] of type " //$NON-NLS-1$
+						+ componentType + ".", e); //$NON-NLS-1$
+				report.setStatus(ConfigurationUpdateStatus.FAILURE);
+				report.setErrorMessageFromThrowable(e);
+			}
+		} catch (Exception e) {
+			LOG.error("Unable to process update request", e); //$NON-NLS-1$
+			report.setStatus(ConfigurationUpdateStatus.FAILURE);
+			report.setErrorMessageFromThrowable(e);
+		}
+	}
+
+	/**
+	 * @return
+	 * @throws Exception
+	 */
+	protected Map<String, ManagedProperty> getManagedProperties()
+			throws Exception {
+		return null;
+	}
+
+	/**
+	 * @param managedComponent
+	 * @throws Exception
+	 */
+	protected void updateComponent(ManagedComponent managedComponent)
+			throws Exception {
+		log.trace("Updating " + this.name + " with component " //$NON-NLS-1$ //$NON-NLS-2$
+				+ managedComponent.toString() + "..."); //$NON-NLS-1$
+		ManagementView managementView = getConnection().getManagementView();
+		managementView.updateComponent(managedComponent);
+
+	}
+
+	@Override
+	public void deleteResource() throws Exception {
+
+		DeploymentManager deploymentManager = getConnection()
+				.getDeploymentManager();
+		
+		log.debug("Stopping deployment [" + this.deploymentUrl + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
+		DeploymentProgress progress = deploymentManager
+				.stop(this.deploymentUrl);
+		DeploymentStatus stopStatus = DeploymentUtils.run(progress);
+		if (stopStatus.isFailed()) {
+			log.error("Failed to stop deployment '" + this.deploymentUrl //$NON-NLS-1$
+					+ "'.", stopStatus.getFailure()); //$NON-NLS-1$
+			throw new Exception("Failed to stop deployment '" //$NON-NLS-1$
+					+ this.deploymentName + "' - cause: " //$NON-NLS-1$
+					+ stopStatus.getFailure());
+		}
+		log.debug("Removing deployment [" + this.deploymentUrl + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
+		progress = deploymentManager.remove(this.deploymentUrl);
+		DeploymentStatus removeStatus = DeploymentUtils.run(progress);
+		if (removeStatus.isFailed()) {
+			log.error("Failed to remove deployment '" + this.deploymentUrl //$NON-NLS-1$
+					+ "'.", removeStatus.getFailure()); //$NON-NLS-1$
+			throw new Exception("Failed to remove deployment '" //$NON-NLS-1$
+					+ this.deploymentName + "' - cause: " //$NON-NLS-1$
+					+ removeStatus.getFailure());
+		}
+
+	}
+
+	@Override
+	public DeployPackagesResponse deployPackages(
+			Set<ResourcePackageDetails> packages,
+			ContentServices contentServices) {
+		// You can only update the one application file referenced by this
+		// resource, so punch out if multiple are
+		// specified.
+		if (packages.size() != 1) {
+			log
+					.warn("Request to update a VDB file contained multiple packages: " //$NON-NLS-1$
+							+ packages);
+			DeployPackagesResponse response = new DeployPackagesResponse(
+					ContentResponseResult.FAILURE);
+			response
+					.setOverallRequestErrorMessage("When updating a VDB, only one VDB can be updated at a time."); //$NON-NLS-1$
+			return response;
+		}
+
+		ResourcePackageDetails packageDetails = packages.iterator().next();
+
+		log.debug("Updating VDB file '" + this.deploymentFile + "' using [" //$NON-NLS-1$ //$NON-NLS-2$
+				+ packageDetails + "]..."); //$NON-NLS-1$
+
+		log.debug("Writing new VDB bits to temporary file..."); //$NON-NLS-1$
+		File tempFile;
+		try {
+			tempFile = writeNewAppBitsToTempFile(contentServices,
+					packageDetails);
+		} catch (Exception e) {
+			return failApplicationDeployment(
+					"Error writing new application bits to temporary file - cause: " //$NON-NLS-1$
+							+ e, packageDetails);
+		}
+		log.debug("Wrote new VDB bits to temporary file '" + tempFile //$NON-NLS-1$
+				+ "'."); //$NON-NLS-1$
+
+		boolean deployExploded = this.deploymentFile.isDirectory();
+
+		// Backup the original app file/dir to <filename>.rej.
+		File backupOfOriginalFile = new File(this.deploymentFile.getPath()
+				+ BACKUP_FILE_EXTENSION);
+		log.debug("Backing up existing VDB '" + this.deploymentFile //$NON-NLS-1$
+				+ "' to '" + backupOfOriginalFile + "'..."); //$NON-NLS-1$ //$NON-NLS-2$
+		try {
+			if (backupOfOriginalFile.exists())
+				FileUtils.forceDelete(backupOfOriginalFile);
+			if (this.deploymentFile.isDirectory())
+				FileUtils.copyDirectory(this.deploymentFile,
+						backupOfOriginalFile, true);
+			else
+				FileUtils.copyFile(this.deploymentFile, backupOfOriginalFile,
+						true);
+		} catch (Exception e) {
+			throw new RuntimeException("Failed to backup existing EAR/WAR '" //$NON-NLS-1$
+					+ this.deploymentFile + "' to '" + backupOfOriginalFile //$NON-NLS-1$
+					+ "'."); //$NON-NLS-1$
+		}
+
+		// Now stop the original app.
+		try {
+			DeploymentManager deploymentManager = getConnection()
+					.getDeploymentManager();
+			DeploymentProgress progress = deploymentManager
+					.stop(this.deploymentUrl);
+			DeploymentUtils.run(progress);
+		} catch (Exception e) {
+			throw new RuntimeException("Failed to stop deployment [" //$NON-NLS-1$
+					+ this.deploymentUrl + "].", e); //$NON-NLS-1$
+		}
+
+		// And then remove it (this will delete the physical file/dir from the
+		// deploy dir).
+		try {
+			DeploymentManager deploymentManager = getConnection()
+					.getDeploymentManager();
+			DeploymentProgress progress = deploymentManager
+					.remove(this.deploymentUrl);
+			DeploymentUtils.run(progress);
+		} catch (Exception e) {
+			throw new RuntimeException("Failed to remove deployment [" //$NON-NLS-1$
+					+ this.deploymentUrl + "].", e); //$NON-NLS-1$
+		}
+
+		// Deploy away!
+		log.debug("Deploying '" + tempFile + "'..."); //$NON-NLS-1$ //$NON-NLS-2$
+		DeploymentManager deploymentManager = getConnection()
+				.getDeploymentManager();
+		try {
+			DeploymentUtils.deployArchive(deploymentManager, tempFile,
+					deployExploded);
+		} catch (Exception e) {
+			// Deploy failed - rollback to the original app file...
+			log.debug("Redeploy failed - rolling back to original archive...", //$NON-NLS-1$
+					e);
+			String errorMessage = ThrowableUtil.getAllMessages(e);
+			try {
+				// Delete the new app, which failed to deploy.
+				FileUtils.forceDelete(this.deploymentFile);
+				// Need to re-deploy the original file - this generally should
+				// succeed.
+				DeploymentUtils.deployArchive(deploymentManager,
+						backupOfOriginalFile, deployExploded);
+				errorMessage += " ***** ROLLED BACK TO ORIGINAL APPLICATION FILE. *****"; //$NON-NLS-1$
+			} catch (Exception e1) {
+				log.debug("Rollback failed!", e1); //$NON-NLS-1$
+				errorMessage += " ***** FAILED TO ROLLBACK TO ORIGINAL APPLICATION FILE. *****: " //$NON-NLS-1$
+						+ ThrowableUtil.getAllMessages(e1);
+			}
+			log.info("Failed to update VDB file '" + this.deploymentFile //$NON-NLS-1$
+					+ "' using [" + packageDetails + "]."); //$NON-NLS-1$ //$NON-NLS-2$
+			return failApplicationDeployment(errorMessage, packageDetails);
+		}
+
+		// Deploy was successful!
+
+		deleteBackupOfOriginalFile(backupOfOriginalFile);
+		persistApplicationVersion(packageDetails, this.deploymentFile);
+
+		DeployPackagesResponse response = new DeployPackagesResponse(
+				ContentResponseResult.SUCCESS);
+		DeployIndividualPackageResponse packageResponse = new DeployIndividualPackageResponse(
+				packageDetails.getKey(), ContentResponseResult.SUCCESS);
+		response.addPackageResponse(packageResponse);
+
+		log.debug("Updated VDB file '" + this.deploymentFile //$NON-NLS-1$
+				+ "' successfully - returning response [" + response + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
+
+		return response;
+	}
+
+	private void deleteBackupOfOriginalFile(File backupOfOriginalFile) {
+		log.debug("Deleting backup of original file '" + backupOfOriginalFile //$NON-NLS-1$
+				+ "'..."); //$NON-NLS-1$
+		try {
+			FileUtils.forceDelete(backupOfOriginalFile);
+		} catch (Exception e) {
+			// not critical.
+			log.warn("Failed to delete backup of original file: " //$NON-NLS-1$
+					+ backupOfOriginalFile);
+		}
+	}
+	
+	private void persistApplicationVersion(ResourcePackageDetails packageDetails, File appFile)
+    {
+        String packageName = appFile.getName();
+        log.debug("Persisting application version '" + packageDetails.getVersion() + "' for package '" + packageName //$NON-NLS-1$ //$NON-NLS-2$
+                + "'"); //$NON-NLS-1$
+        PackageVersions versions = loadPackageVersions();
+        versions.putVersion(packageName, packageDetails.getVersion());
+    }
+
+	private File writeNewAppBitsToTempFile(ContentServices contentServices,
+			ResourcePackageDetails packageDetails) throws Exception {
+		File tempDir = this.resourceContext.getTemporaryDirectory();
+		File tempFile = new File(tempDir, this.deploymentFile.getName());
+
+		OutputStream tempOutputStream = null;
+		try {
+			tempOutputStream = new BufferedOutputStream(new FileOutputStream(
+					tempFile));
+			long bytesWritten = contentServices.downloadPackageBits(
+					this.resourceContext.getContentContext(), packageDetails
+							.getKey(), tempOutputStream, true);
+			log
+					.debug("Wrote " + bytesWritten + " bytes to '" + tempFile //$NON-NLS-1$ //$NON-NLS-2$
+							+ "'."); //$NON-NLS-1$
+		} catch (IOException e) {
+			log.error(
+					"Error writing updated application bits to temporary location: " //$NON-NLS-1$
+							+ tempFile, e);
+			throw e;
+		} finally {
+			if (tempOutputStream != null) {
+				try {
+					tempOutputStream.close();
+				} catch (IOException e) {
+					log.error("Error closing temporary output stream", e); //$NON-NLS-1$
+				}
+			}
+		}
+		if (!tempFile.exists()) {
+			log.error("Temporary file for application update not written to: " //$NON-NLS-1$
+					+ tempFile);
+			throw new Exception();
+		}
+		return tempFile;
+	}
+
+	/**
+	 * Creates the necessary transfer objects to report a failed application
+	 * deployment (update).
+	 * 
+	 * @param errorMessage
+	 *            reason the deploy failed
+	 * @param packageDetails
+	 *            describes the update being made
+	 * @return response populated to reflect a failure
+	 */
+	private DeployPackagesResponse failApplicationDeployment(
+			String errorMessage, ResourcePackageDetails packageDetails) {
+		DeployPackagesResponse response = new DeployPackagesResponse(
+				ContentResponseResult.FAILURE);
+
+		DeployIndividualPackageResponse packageResponse = new DeployIndividualPackageResponse(
+				packageDetails.getKey(), ContentResponseResult.FAILURE);
+		packageResponse.setErrorMessage(errorMessage);
+
+		response.addPackageResponse(packageResponse);
+
+		return response;
+	}
+
+	@Override
+	public Set<ResourcePackageDetails> discoverDeployedPackages(PackageType arg0) {
+
+		// PLEASE DO NOT REMOVE THIS METHOD. IT IS REQUIRED FOR THE CONTENT TAB.
+
+		Configuration pluginConfig = this.resourceContext
+				.getPluginConfiguration();
+		this.deploymentUrl = pluginConfig.getSimple("url").getStringValue(); //$NON-NLS-1$
+
+		if (this.deploymentUrl != null) {
+			this.deploymentFile = new File(this.deploymentUrl
+					.substring(deploymentUrl.indexOf(":/") + 1)); //$NON-NLS-1$
+		}
+
+		if (!deploymentFile.exists())
+			throw new IllegalStateException("Deployment file '" //$NON-NLS-1$
+					+ this.deploymentFile + "' for " + this.getComponentType() //$NON-NLS-1$
+					+ " does not exist."); //$NON-NLS-1$
+
+		String fileName = deploymentFile.getName();
+		org.rhq.core.pluginapi.content.version.PackageVersions packageVersions = loadPackageVersions();
+		String version = packageVersions.getVersion(fileName);
+		if (version == null) {
+			// This is either the first time we've discovered this VDB, or
+			// someone purged the PC's data dir.
+			version = "1.0"; //$NON-NLS-1$
+			packageVersions.putVersion(fileName, version);
+			packageVersions.saveToDisk();
+		}
+
+		// Package name is the deployment's file name (e.g. foo.ear).
+		PackageDetailsKey key = new PackageDetailsKey(fileName, version,
+				PKG_TYPE_VDB, ARCHITECTURE);
+		ResourcePackageDetails packageDetails = new ResourcePackageDetails(key);
+		packageDetails.setFileName(fileName);
+		packageDetails.setLocation(deploymentFile.getPath());
+		if (!deploymentFile.isDirectory())
+			packageDetails.setFileSize(deploymentFile.length());
+		packageDetails.setFileCreatedDate(null);  
+		Set<ResourcePackageDetails> packages = new HashSet<ResourcePackageDetails>();
+		packages.add(packageDetails);
+
+		return packages;
+	}
+
+	@Override
+	public List<DeployPackageStep> generateInstallationSteps(
+			ResourcePackageDetails arg0) {
+		return null;
+	}
+
+	@Override
+	public RemovePackagesResponse removePackages(
+			Set<ResourcePackageDetails> arg0) {
+		return null;
+	}
+
+	@Override
+	public InputStream retrievePackageBits(ResourcePackageDetails packageDetails) {
+		return null;
+	}
+
+	protected static Configuration getDefaultPluginConfiguration(
+			ResourceType resourceType) {
+		ConfigurationTemplate pluginConfigDefaultTemplate = resourceType
+				.getPluginConfigurationDefinition().getDefaultTemplate();
+		return (pluginConfigDefaultTemplate != null) ? pluginConfigDefaultTemplate
+				.createConfiguration()
+				: new Configuration();
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @see
+	 * org.rhq.core.pluginapi.inventory.CreateChildResourceFacet#createResource
+	 * (org.rhq.core.pluginapi.inventory.CreateResourceReport)
+	 */
+	@Override
+	public CreateResourceReport createResource(CreateResourceReport report) {
+		ResourceType resourceType = report.getResourceType();
+		// if (resourceType.getName().equals("Translators")) {
+		// createConfigurationBasedResource(report);
+		// } else {
+		createContentBasedResource(report);
+		// }
+
+		return report;
+	}
+
+	private CreateResourceReport createConfigurationBasedResource(
+			CreateResourceReport createResourceReport) {
+		ResourceType resourceType = createResourceReport.getResourceType();
+		Configuration defaultPluginConfig = getDefaultPluginConfiguration(resourceType);
+		Configuration resourceConfig = createResourceReport
+				.getResourceConfiguration();
+		String resourceName = getResourceName(defaultPluginConfig,
+				resourceConfig);
+		ComponentType componentType = ProfileServiceUtil
+				.getComponentType(resourceType);
+		ManagementView managementView = null;
+		;
+		managementView = getConnection().getManagementView();
+
+		if (ProfileServiceUtil.isManagedComponent(getConnection(),
+				resourceName, componentType)) {
+			createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+			createResourceReport.setErrorMessage("A " + resourceType.getName() //$NON-NLS-1$
+					+ " named '" + resourceName + "' already exists."); //$NON-NLS-1$ //$NON-NLS-2$
+			return createResourceReport;
+		}
+
+		createResourceReport.setResourceName(resourceName);
+		String resourceKey = getResourceKey(resourceType, resourceName);
+		createResourceReport.setResourceKey(resourceKey);
+
+		PropertySimple templateNameProperty = resourceConfig
+				.getSimple(TranslatorComponent.Config.TEMPLATE_NAME);
+		String templateName = templateNameProperty.getStringValue();
+
+		DeploymentTemplateInfo template;
+		try {
+			template = managementView.getTemplate(templateName);
+			Map<String, ManagedProperty> managedProperties = template.getProperties();
+
+			ProfileServiceUtil.convertConfigurationToManagedProperties(managedProperties, resourceConfig, resourceType, null);
+
+			LOG.debug("Applying template [" + templateName //$NON-NLS-1$
+					+ "] to create ManagedComponent of type [" + componentType //$NON-NLS-1$
+					+ "]..."); //$NON-NLS-1$
+			try {
+				managementView.applyTemplate(resourceName, template);
+				managementView.process();
+				createResourceReport.setStatus(CreateResourceStatus.SUCCESS);
+			} catch (Exception e) {
+				LOG.error("Unable to apply template [" + templateName //$NON-NLS-1$
+						+ "] to create ManagedComponent of type " //$NON-NLS-1$
+						+ componentType + ".", e); //$NON-NLS-1$
+				createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+				createResourceReport.setException(e);
+			}
+		} catch (NoSuchDeploymentException e) {
+			LOG.error("Unable to find template [" + templateName + "].", e); //$NON-NLS-1$ //$NON-NLS-2$
+			createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+			createResourceReport.setException(e);
+		} catch (Exception e) {
+			LOG.error("Unable to process create request", e); //$NON-NLS-1$
+			createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+			createResourceReport.setException(e);
+		}
+		return createResourceReport;
+	}
+
+	protected void createContentBasedResource(
+			CreateResourceReport createResourceReport) {
+
+		ResourcePackageDetails details = createResourceReport
+				.getPackageDetails();
+		PackageDetailsKey key = details.getKey();
+		// This is the full path to a temporary file which was written by the UI
+		// layer.
+		String archivePath = key.getName();
+
+		try {
+			File archiveFile = new File(archivePath);
+
+			if (!DeploymentUtils.hasCorrectExtension(archiveFile.getName(),
+					resourceContext.getResourceType())) {
+				createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+				createResourceReport
+						.setErrorMessage("Incorrect extension specified on filename [" //$NON-NLS-1$
+								+ archivePath + "]"); //$NON-NLS-1$
+
+			}
+
+			DeploymentManager deploymentManager = getConnection()
+					.getDeploymentManager();
+			DeploymentUtils
+					.deployArchive(deploymentManager, archiveFile, false);
+
+			deploymentName = archivePath;
+			createResourceReport.setResourceName(archivePath);
+			createResourceReport.setResourceKey(archivePath);
+			createResourceReport.setStatus(CreateResourceStatus.SUCCESS);
+
+		} catch (Throwable t) {
+			log.error("Error deploying application for report: " //$NON-NLS-1$
+					+ createResourceReport, t);
+			createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+			createResourceReport.setException(t);
+		}
+
+	}
+
+	private static String getResourceName(Configuration pluginConfig,
+			Configuration resourceConfig) {
+		PropertySimple resourceNameProp = pluginConfig
+				.getSimple(TranslatorComponent.Config.RESOURCE_NAME);
+		if (resourceNameProp == null
+				|| resourceNameProp.getStringValue() == null)
+			throw new IllegalStateException("Property [" //$NON-NLS-1$
+					+ TranslatorComponent.Config.RESOURCE_NAME
+					+ "] is not defined in the default plugin configuration."); //$NON-NLS-1$
+		String resourceNamePropName = resourceNameProp.getStringValue();
+		PropertySimple propToUseAsResourceName = resourceConfig
+				.getSimple(resourceNamePropName);
+		if (propToUseAsResourceName == null)
+			throw new IllegalStateException("Property [" + resourceNamePropName //$NON-NLS-1$
+					+ "] is not defined in initial Resource configuration."); //$NON-NLS-1$
+		return propToUseAsResourceName.getStringValue();
+	}
+
+	private String getResourceKey(ResourceType resourceType, String resourceName) {
+		ComponentType componentType = ProfileServiceUtil
+				.getComponentType(resourceType);
+		if (componentType == null)
+			throw new IllegalStateException("Unable to map " + resourceType //$NON-NLS-1$
+					+ " to a ComponentType."); //$NON-NLS-1$
+		return componentType.getType() + ":" + componentType.getSubtype() + ":" //$NON-NLS-1$ //$NON-NLS-2$
+				+ resourceName;
+	}
+
+	/**
+	 * Returns an instantiated and loaded versions store access point.
+	 * 
+	 * @return will not be <code>null</code>
+	 */
+	private org.rhq.core.pluginapi.content.version.PackageVersions loadPackageVersions() {
+		if (this.versions == null) {
+			ResourceType resourceType = resourceContext.getResourceType();
+			String pluginName = resourceType.getPlugin();
+			File dataDirectoryFile = resourceContext.getDataDirectory();
+			dataDirectoryFile.mkdirs();
+			String dataDirectory = dataDirectoryFile.getAbsolutePath();
+			log.trace("Creating application versions store with plugin name [" //$NON-NLS-1$
+					+ pluginName + "] and data directory [" + dataDirectory //$NON-NLS-1$
+					+ "]"); //$NON-NLS-1$
+			this.versions = new PackageVersions(pluginName, dataDirectory);
+			this.versions.loadFromDisk();
+		}
+
+		return this.versions;
+	}
+
+}

Deleted: tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
===================================================================
--- branches/7.2.x/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,271 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.naming.NamingException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.deployers.spi.management.ManagementView;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.managed.api.RunState;
-import org.mc4j.ems.connection.EmsConnection;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.domain.measurement.AvailabilityType;
-import org.rhq.core.domain.measurement.MeasurementDataNumeric;
-import org.rhq.core.domain.measurement.MeasurementReport;
-import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
-import org.rhq.core.pluginapi.inventory.ResourceContext;
-import org.rhq.plugins.jbossas5.ApplicationServerComponent;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.rhq.admin.DQPManagementView;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-import org.teiid.rhq.plugin.util.PluginConstants.Operation;
-import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform;
-
-/**
- * 
- */
-public class PlatformComponent extends Facet {
-	private final Log LOG = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-	String[] PLATFORM_SERVICES_NAMES = { "RuntimeEngineDeployer", //$NON-NLS-1$
-			"BufferService", "SessionService", "JdbcSocketConfiguration" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
-	@Override
-	public void start(ResourceContext context) {
-		this.setComponentName(context.getPluginConfiguration().getSimpleValue(	"name", null)); //$NON-NLS-1$
-		this.resourceConfiguration = context.getPluginConfiguration();
-		super.start(context);
-	}
-
-	/**
-	 * @see org.teiid.rhq.plugin.Facet#getComponentType()
-	 * @since 7.0
-	 */
-	@Override
-	String getComponentType() {
-		return PluginConstants.ComponentType.Platform.NAME;
-	}
-
-	@Override
-	public AvailabilityType getAvailability() {
-
-		RunState runState;
-		try {
-			runState = ProfileServiceUtil.getRuntimeEngineDeployer(getConnection()).getRunState();
-		} catch (NamingException e) {
-			LOG	.debug("Naming exception getting: " + PluginConstants.ComponentType.Platform.TEIID_RUNTIME_ENGINE); //$NON-NLS-1$
-			return AvailabilityType.DOWN;
-		} catch (Exception e) {
-			LOG	.debug("Exception getting: " 	+ PluginConstants.ComponentType.Platform.TEIID_RUNTIME_ENGINE); //$NON-NLS-1$
-			return AvailabilityType.DOWN;
-		}
-		return (runState == RunState.RUNNING) ? AvailabilityType.UP: AvailabilityType.DOWN;
-	}
-
-	@Override
-	protected void setOperationArguments(String name,
-			Configuration configuration, Map<String, Object> valueMap) {
-		// Parameter logic for System Operations
-		if (name.equals(Platform.Operations.KILL_REQUEST)) {
-			valueMap.put(Operation.Value.REQUEST_ID, configuration.getSimple(Operation.Value.REQUEST_ID).getLongValue());
-			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(Operation.Value.SESSION_ID).getLongValue());
-		} else if (name.equals(Platform.Operations.KILL_REQUEST)) {
-			valueMap.put(Operation.Value.TRANSACTION_ID, configuration.getSimple(Operation.Value.TRANSACTION_ID).getLongValue());
-		} else if (name.equals(Platform.Operations.KILL_SESSION)) {
-			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(Operation.Value.SESSION_ID).getLongValue());
-		} else if (name.equals(Platform.Operations.DEPLOY_VDB_BY_URL)) {
-			valueMap.put(Operation.Value.VDB_URL, configuration.getSimple(Operation.Value.VDB_URL).getStringValue());
-			valueMap.put(Operation.Value.VDB_DEPLOY_NAME, configuration.getSimple(Operation.Value.VDB_DEPLOY_NAME).getStringValue());
-			valueMap.put(Operation.Value.VDB_VERSION, configuration.getSimple(Operation.Value.VDB_VERSION).getIntegerValue());
-		}
-	}
-
-	@Override
-	public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> requests) throws Exception {
-
-		DQPManagementView view = new DQPManagementView();
-
-		Map<String, Object> valueMap = new HashMap<String, Object>();
-
-		try {
-			for (MeasurementScheduleRequest request : requests) {
-				String name = request.getName();
-				LOG.debug("Measurement name = " + name); //$NON-NLS-1$
-
-				// Initialize any parameters to be used in the retrieval of
-				// metric values
-
-				Object metric = view.getMetric(getConnection(),
-						getComponentType(), this.getComponentIdentifier(),
-						name, valueMap);
-
-				if (metric instanceof Double) {
-					report.addData(new MeasurementDataNumeric(request, (Double) metric));
-				}
-				else if (metric instanceof Integer ){
-					report.addData(new MeasurementDataNumeric(request, new Double(((Integer)metric).doubleValue())));
-				}
-				else if (metric instanceof Long){
-					report.addData(new MeasurementDataNumeric(request, new Double(((Long)metric).longValue())));
-				}
-				else {
-					LOG.error("Metric value must be a numeric value"); //$NON-NLS-1$
-				}
-			}
-		} catch (Exception e) {
-			LOG.error("Failed to obtain measurement [" + name 	+ "]. Cause: " + e); //$NON-NLS-1$ //$NON-NLS-2$
-			throw (e);
-		}
-	}
-
-	@Override
-	public void stop() {
-		// TODO Auto-generated method stub
-		super.stop();
-	}
-
-	@Override
-	public void updateResourceConfiguration(ConfigurationUpdateReport report) {
-
-		resourceConfiguration = report.getConfiguration().deepCopy();
-
-		Configuration resourceConfig = report.getConfiguration();
-
-		ManagementView managementView = null;
-		ComponentType componentType = new ComponentType(
-				PluginConstants.ComponentType.Platform.TEIID_TYPE,
-				PluginConstants.ComponentType.Platform.TEIID_SUB_TYPE);
-
-		ManagedComponent managedComponent = null;
-		report.setStatus(ConfigurationUpdateStatus.SUCCESS);
-		try {
-
-			managementView = getConnection().getManagementView();
-
-			for (String serviceName : PLATFORM_SERVICES_NAMES) {
-
-				managedComponent = managementView.getComponent(serviceName, componentType);
-				Map<String, ManagedProperty> managedProperties = managedComponent.getProperties();
-
-				ProfileServiceUtil.convertConfigurationToManagedProperties(managedProperties, resourceConfig, resourceContext.getResourceType());
-
-				try {
-					managementView.updateComponent(managedComponent);
-				} catch (Exception e) {
-					LOG.error("Unable to update component [" //$NON-NLS-1$
-							+ managedComponent.getName() + "] of type " //$NON-NLS-1$
-							+ componentType + ".", e); //$NON-NLS-1$
-					report.setStatus(ConfigurationUpdateStatus.FAILURE);
-					report.setErrorMessageFromThrowable(e);
-				}
-			}
-		} catch (Exception e) {
-			LOG.error("Unable to process update request", e); //$NON-NLS-1$
-			report.setStatus(ConfigurationUpdateStatus.FAILURE);
-			report.setErrorMessageFromThrowable(e);
-		}
-
-	}
-
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.teiid.rhq.plugin.Facet#loadResourceConfiguration()
-	 */
-	@Override
-	public Configuration loadResourceConfiguration() {
-
-		// Get plugin config
-		Configuration c = resourceContext.getPluginConfiguration();
-
-		getProperties(c);
-
-		return c;
-
-	}
-
-	/**
-	 * @param mc
-	 * @param configuration
-	 * @throws Exception
-	 */
-	private void getProperties(Configuration configuration) {
-
-		// Get all ManagedComponents of type Teiid and subtype dqp
-		Set<ManagedComponent> mcSet = null;
-		try {
-			mcSet = ProfileServiceUtil.getManagedComponents(getConnection(),
-					new org.jboss.managed.api.ComponentType(
-									PluginConstants.ComponentType.Platform.TEIID_TYPE,
-									PluginConstants.ComponentType.Platform.TEIID_SUB_TYPE));
-		} catch (NamingException e) {
-			LOG.error("NamingException getting components in Platform loadConfiguration(): "	+ e.getMessage()); //$NON-NLS-1$
-		} catch (Exception e) {
-			LOG.error("Exception getting components in Platform loadConfiguration(): "	+ e.getMessage()); //$NON-NLS-1$
-		}
-
-		for (ManagedComponent mc : mcSet) {
-			Map<String, ManagedProperty> mcMap = mc.getProperties();
-			setProperties(mcMap, configuration);
-		}
-	}
-
-	/**
-	 * @param mcMap
-	 * @param configuration
-	 */
-	private void setProperties(Map<String, ManagedProperty> mcMap,
-			Configuration configuration) {
-		for (ManagedProperty mProp : mcMap.values()) {
-			try {
-				String value = ProfileServiceUtil.stringValue(mProp.getValue());
-				PropertySimple prop = new PropertySimple(mProp.getName(), value);
-				configuration.put(prop);
-			} catch (Exception e) {
-				LOG.error("Exception setting properties in Platform loadConfiguration(): "	+ e.getMessage()); //$NON-NLS-1$
-			}
-		}
-	}
-
-	@Override
-	public ProfileServiceConnection getConnection() {
-		return ((ApplicationServerComponent) this.resourceContext.getParentResourceComponent()).getConnection();
-	}
-
-	@Override
-	public EmsConnection getEmsConnection() {
-		return null;
-	}
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java (from rev 2707, branches/7.2.x/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,268 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import javax.naming.NamingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.api.RunState;
+import org.mc4j.ems.connection.EmsConnection;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.measurement.AvailabilityType;
+import org.rhq.core.domain.measurement.MeasurementDataNumeric;
+import org.rhq.core.domain.measurement.MeasurementReport;
+import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
+import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
+import org.rhq.core.pluginapi.inventory.ResourceContext;
+import org.rhq.plugins.jbossas5.ApplicationServerComponent;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.rhq.admin.DQPManagementView;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+import org.teiid.rhq.plugin.util.PluginConstants.Operation;
+import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform;
+
+/**
+ * 
+ */
+public class PlatformComponent extends Facet {
+	private final Log LOG = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+	@Override
+	public void start(ResourceContext context) {
+		this.setComponentName(context.getPluginConfiguration().getSimpleValue(	"name", null)); //$NON-NLS-1$
+		this.resourceConfiguration = context.getPluginConfiguration();
+		super.start(context);
+	}
+
+	/**
+	 * @see org.teiid.rhq.plugin.Facet#getComponentType()
+	 * @since 7.0
+	 */
+	@Override
+	String getComponentType() {
+		return PluginConstants.ComponentType.Platform.NAME;
+	}
+
+	@Override
+	public AvailabilityType getAvailability() {
+
+		RunState runState;
+		try {
+			runState = ProfileServiceUtil.getRuntimeEngineDeployer(getConnection()).getRunState();
+		} catch (NamingException e) {
+			LOG	.debug("Naming exception getting: " + PluginConstants.ComponentType.Platform.TEIID_RUNTIME_ENGINE); //$NON-NLS-1$
+			return AvailabilityType.DOWN;
+		} catch (Exception e) {
+			LOG	.debug("Exception getting: " 	+ PluginConstants.ComponentType.Platform.TEIID_RUNTIME_ENGINE); //$NON-NLS-1$
+			return AvailabilityType.DOWN;
+		}
+		return (runState == RunState.RUNNING) ? AvailabilityType.UP: AvailabilityType.DOWN;
+	}
+
+	@Override
+	protected void setOperationArguments(String name,
+			Configuration configuration, Map<String, Object> valueMap) {
+		// Parameter logic for System Operations
+		if (name.equals(Platform.Operations.KILL_REQUEST)) {
+			valueMap.put(Operation.Value.REQUEST_ID, configuration.getSimple(Operation.Value.REQUEST_ID).getLongValue());
+			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(Operation.Value.SESSION_ID).getLongValue());
+		} else if (name.equals(Platform.Operations.KILL_REQUEST)) {
+			valueMap.put(Operation.Value.TRANSACTION_ID, configuration.getSimple(Operation.Value.TRANSACTION_ID).getLongValue());
+		} else if (name.equals(Platform.Operations.KILL_SESSION)) {
+			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(Operation.Value.SESSION_ID).getLongValue());
+		} else if (name.equals(Platform.Operations.DEPLOY_VDB_BY_URL)) {
+			valueMap.put(Operation.Value.VDB_URL, configuration.getSimple(Operation.Value.VDB_URL).getStringValue());
+			valueMap.put(Operation.Value.VDB_DEPLOY_NAME, configuration.getSimple(Operation.Value.VDB_DEPLOY_NAME).getStringValue());
+			valueMap.put(Operation.Value.VDB_VERSION, configuration.getSimple(Operation.Value.VDB_VERSION).getIntegerValue());
+		}
+	}
+
+	@Override
+	public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> requests) throws Exception {
+
+		DQPManagementView view = new DQPManagementView();
+
+		Map<String, Object> valueMap = new HashMap<String, Object>();
+
+		try {
+			for (MeasurementScheduleRequest request : requests) {
+				String name = request.getName();
+				LOG.debug("Measurement name = " + name); //$NON-NLS-1$
+
+				// Initialize any parameters to be used in the retrieval of
+				// metric values
+
+				Object metric = view.getMetric(getConnection(),
+						getComponentType(), this.getComponentIdentifier(),
+						name, valueMap);
+
+				if (metric instanceof Double) {
+					report.addData(new MeasurementDataNumeric(request, (Double) metric));
+				}
+				else if (metric instanceof Integer ){
+					report.addData(new MeasurementDataNumeric(request, new Double(((Integer)metric).doubleValue())));
+				}
+				else if (metric instanceof Long){
+					report.addData(new MeasurementDataNumeric(request, new Double(((Long)metric).longValue())));
+				}
+				else {
+					LOG.error("Metric value must be a numeric value"); //$NON-NLS-1$
+				}
+			}
+		} catch (Exception e) {
+			LOG.error("Failed to obtain measurement [" + name 	+ "]. Cause: " + e); //$NON-NLS-1$ //$NON-NLS-2$
+			throw (e);
+		}
+	}
+
+	@Override
+	public void stop() {
+		// TODO Auto-generated method stub
+		super.stop();
+	}
+
+	@Override
+	public void updateResourceConfiguration(ConfigurationUpdateReport report) {
+
+		resourceConfiguration = report.getConfiguration().deepCopy();
+
+		Configuration resourceConfig = report.getConfiguration();
+
+		ManagementView managementView = null;
+		ComponentType componentType = new ComponentType(
+				PluginConstants.ComponentType.Platform.TEIID_TYPE,
+				PluginConstants.ComponentType.Platform.TEIID_SUB_TYPE);
+
+		report.setStatus(ConfigurationUpdateStatus.SUCCESS);
+		try {
+
+			managementView = getConnection().getManagementView();
+			Set<ManagedComponent> allComponents = managementView.getComponentsForType(componentType);
+			
+			for (ManagedComponent managedComponent : allComponents) {
+				
+				Map<String, ManagedProperty> managedProperties = managedComponent.getProperties();
+
+				
+				ProfileServiceUtil.convertConfigurationToManagedProperties(managedProperties, resourceConfig, resourceContext.getResourceType(), managedComponent.getName());
+
+				try {
+					managementView.updateComponent(managedComponent);
+				} catch (Exception e) {
+					LOG.error("Unable to update component [" //$NON-NLS-1$
+							+ managedComponent.getName() + "] of type " //$NON-NLS-1$
+							+ componentType + ".", e); //$NON-NLS-1$
+					report.setStatus(ConfigurationUpdateStatus.FAILURE);
+					report.setErrorMessageFromThrowable(e);
+				}
+			}
+		} catch (Exception e) {
+			LOG.error("Unable to process update request", e); //$NON-NLS-1$
+			report.setStatus(ConfigurationUpdateStatus.FAILURE);
+			report.setErrorMessageFromThrowable(e);
+		}
+
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @see org.teiid.rhq.plugin.Facet#loadResourceConfiguration()
+	 */
+	@Override
+	public Configuration loadResourceConfiguration() {
+
+		// Get plugin config
+		Configuration c = resourceContext.getPluginConfiguration();
+
+		getProperties(c);
+
+		return c;
+
+	}
+
+	/**
+	 * @param mc
+	 * @param configuration
+	 * @throws Exception
+	 */
+	private void getProperties(Configuration configuration) {
+
+		// Get all ManagedComponents of type Teiid and subtype dqp
+		Set<ManagedComponent> mcSet = null;
+		try {
+			mcSet = ProfileServiceUtil.getManagedComponents(getConnection(),
+					new org.jboss.managed.api.ComponentType(
+									PluginConstants.ComponentType.Platform.TEIID_TYPE,
+									PluginConstants.ComponentType.Platform.TEIID_SUB_TYPE));
+		} catch (NamingException e) {
+			LOG.error("NamingException getting components in Platform loadConfiguration(): "	+ e.getMessage()); //$NON-NLS-1$
+		} catch (Exception e) {
+			LOG.error("Exception getting components in Platform loadConfiguration(): "	+ e.getMessage()); //$NON-NLS-1$
+		}
+		
+		for (ManagedComponent mc : mcSet) {
+			Map<String, ManagedProperty> mcMap = mc.getProperties();
+			String name = mc.getName();			
+			setProperties(name, mcMap, configuration);
+		}
+	}
+
+	/**
+	 * @param mcMap
+	 * @param configuration
+	 */
+	private void setProperties(String compName, Map<String, ManagedProperty> mcMap, Configuration configuration) {
+		for (ManagedProperty mProp : mcMap.values()) {
+			try {
+				String value = ProfileServiceUtil.stringValue(mProp.getValue());
+				PropertySimple prop = new PropertySimple(compName+"."+mProp.getName(), value); //$NON-NLS-1$
+				configuration.put(prop);
+			} catch (Exception e) {
+				LOG.error("Exception setting properties in Platform loadConfiguration(): "	+ e.getMessage()); //$NON-NLS-1$
+			}
+		}
+	}
+
+	@Override
+	public ProfileServiceConnection getConnection() {
+		return ((ApplicationServerComponent) this.resourceContext.getParentResourceComponent()).getConnection();
+	}
+
+	@Override
+	public EmsConnection getEmsConnection() {
+		return null;
+	}
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java
===================================================================
--- branches/7.2.x/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,620 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.rhq.plugin.util;
-
-import java.io.File;
-import java.io.Serializable;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.naming.NamingException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.deployers.spi.management.KnownDeploymentTypes;
-import org.jboss.deployers.spi.management.ManagementView;
-import org.jboss.deployers.spi.management.deploy.DeploymentManager;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.ManagedCommon;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedDeployment;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.managed.api.annotation.ViewUse;
-import org.jboss.metatype.api.types.MapCompositeMetaType;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.types.SimpleMetaType;
-import org.jboss.metatype.api.values.EnumValue;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.SimpleValue;
-import org.jboss.metatype.api.values.SimpleValueSupport;
-import org.jboss.profileservice.spi.ProfileService;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.Property;
-import org.rhq.core.domain.configuration.PropertyMap;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
-import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
-import org.rhq.core.domain.configuration.definition.PropertyDefinition;
-import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
-import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
-import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
-import org.rhq.core.domain.configuration.definition.PropertySimpleType;
-import org.rhq.core.domain.resource.ResourceType;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.rhq.plugin.TranslatorComponent;
-import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
-import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
-
-import com.sun.istack.NotNull;
-
-public class ProfileServiceUtil {
-
-	protected final static Log LOG = LogFactory
-			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY); 
-	private static ComponentType DQPTYPE = new ComponentType("teiid", "dqp"); //$NON-NLS-1$ //$NON-NLS-2$
-	private static String DQPNAME = "RuntimeEngineDeployer"; //$NON-NLS-1$
-	private static String BUFFERSERVICE = "BufferService"; //$NON-NLS-1$
-	private static final Map<String, ComponentType> COMPONENT_TYPE_CACHE = new HashMap<String, ComponentType>();
-	
-	protected static final String PLUGIN = "ProfileService"; //$NON-NLS-1$
-
-	public static ComponentType getComponentType(
-			@NotNull ResourceType resourceType) {
-		String resourceTypeName = resourceType.getName();
-		if (COMPONENT_TYPE_CACHE.containsKey(resourceTypeName))
-			return COMPONENT_TYPE_CACHE.get(resourceTypeName);
-		Configuration defaultPluginConfig = getDefaultPluginConfiguration(resourceType);
-		String type = defaultPluginConfig.getSimpleValue(
-				TranslatorComponent.Config.COMPONENT_TYPE, null);
-		if (type == null || type.equals("")) //$NON-NLS-1$
-			throw new IllegalStateException(
-					"Required plugin configuration property '" //$NON-NLS-1$
-							+ TranslatorComponent.Config.COMPONENT_TYPE
-							+ "' is not defined in default template."); //$NON-NLS-1$
-		String subtype = defaultPluginConfig.getSimpleValue(
-				TranslatorComponent.Config.COMPONENT_SUBTYPE, null);
-		if (subtype == null || subtype.equals("")) //$NON-NLS-1$
-			throw new IllegalStateException(
-					"Required plugin configuration property '" //$NON-NLS-1$
-							+ TranslatorComponent.Config.COMPONENT_SUBTYPE 
-							+ "' is not defined in default template."); //$NON-NLS-1$
-		ComponentType componentType = new ComponentType(type, subtype);
-		COMPONENT_TYPE_CACHE.put(resourceTypeName, componentType);
-		return componentType;
-	}
-
-	private static Configuration getDefaultPluginConfiguration(
-			ResourceType resourceType) {
-		ConfigurationTemplate pluginConfigDefaultTemplate = resourceType
-				.getPluginConfigurationDefinition().getDefaultTemplate();
-		return (pluginConfigDefaultTemplate != null) ? pluginConfigDefaultTemplate
-				.createConfiguration()
-				: new Configuration();
-	}
-
-	/**
-	 * @param name
-	 * @param componentType
-	 * @return
-	 */
-	public static boolean isManagedComponent(
-			ProfileServiceConnection connection, String name,
-			ComponentType componentType) {
-		boolean isDeployed = false;
-		if (name != null) {
-			try {
-				ManagedComponent component = getManagedComponent(connection,
-						componentType, name);
-				if (component != null)
-					isDeployed = true;
-			} catch (Exception e) {
-				// Setting it to true to be safe than sorry, since there might
-				// be a component
-				// already deployed in the AS.
-				isDeployed = true;
-			}
-		}
-		return isDeployed;
-	}
-
-	/**
-	 * Get the passed in {@link ManagedComponent}
-	 * 
-	 * @return {@link ManagedComponent}
-	 * @throws NamingException
-	 * @throws Exception
-	 */
-	public static ManagedComponent getManagedComponent(
-			ProfileServiceConnection connection, ComponentType componentType,
-			String componentName) throws NamingException, Exception {
-		ManagedComponent mc = connection.getManagementView().getComponent(
-				componentName, componentType);
-
-		return mc;
-	}
-
-	/**
-	 * Get the {@link ManagedComponent} for the {@link ComponentType} and sub
-	 * type.
-	 * 
-	 * @return Set of {@link ManagedComponent}s
-	 * @throws NamingException
-	 *             , Exception
-	 * @throws Exception
-	 */
-	public static Set<ManagedComponent> getManagedComponents(ProfileServiceConnection connection,
-			ComponentType componentType) throws NamingException, Exception {
-		
-		Set<ManagedComponent> mcSet = connection.getManagementView().getComponentsForType(componentType);
-
-		return mcSet;
-	}
-
-	/**
-	 * @param {@link ManagementView}
-	 * @return
-	 */
-	public static ManagementView getManagementView(ProfileService ps,
-			boolean load) {
-		ManagementView mv = ps.getViewManager();
-		if (load) {
-			mv.load();
-		}
-		return mv;
-	}
-
-	/**
-	 * Get the {@link DeploymentManager} from the ProfileService
-	 * 
-	 * @return DeploymentManager
-	 * @throws NamingException
-	 * @throws Exception
-	 */
-	public static DeploymentManager getDeploymentManager(ProfileServiceConnection connection)
-			throws NamingException, Exception {
-
-		return connection.getDeploymentManager();
-	}
-
-	/**
-	 * @return {@link File}
-	 * @throws NamingException
-	 *             , Exception
-	 */
-	public static File getDeployDirectory(ProfileServiceConnection connection) throws NamingException, Exception {
-		Set<ManagedDeployment> warDeployments;
-		try {
-			warDeployments = connection.getManagementView()
-					.getDeploymentsForType(KnownDeploymentTypes.JavaEEWebApplication
-							.getType());
-		} catch (Exception e) {
-			throw new IllegalStateException(e);
-		}
-		ManagedDeployment standaloneWarDeployment = null;
-		for (ManagedDeployment warDeployment : warDeployments) {
-			if (warDeployment.getParent() == null) {
-				standaloneWarDeployment = warDeployment;
-				break;
-			}
-		}
-		if (standaloneWarDeployment == null)
-			// This could happen if no standalone WARs, including the admin
-			// console WAR, have been fully deployed yet.
-			return null;
-		URL warUrl;
-		try {
-			warUrl = new URL(standaloneWarDeployment.getName());
-		} catch (MalformedURLException e) {
-			throw new IllegalStateException(e);
-		}
-		File warFile = new File(warUrl.getPath());
-		File deployDir = warFile.getParentFile();
-		return deployDir;
-	}
-
-	public static ManagedComponent getRuntimeEngineDeployer(
-			ProfileServiceConnection connection) throws NamingException,
-			Exception {
-
-		return getManagedComponent(connection, DQPTYPE, DQPNAME);
-	}
-	
-	public static ManagedComponent getBufferService(
-			ProfileServiceConnection connection) throws NamingException,
-			Exception {
-
-		return getManagedComponent(connection, DQPTYPE, BUFFERSERVICE);
-	}
-
-	public static String stringValue(MetaValue v1) throws Exception {
-		if (v1 != null) {
-			MetaType type = v1.getMetaType();
-			if (type instanceof SimpleMetaType) {
-				SimpleValue simple = (SimpleValue) v1;
-				return simple.getValue().toString();
-			}
-			throw new Exception("Failed to convert value to string value"); //$NON-NLS-1$
-		}
-		return null;
-	}
-
-	public static Boolean booleanValue(MetaValue v1) throws Exception {
-		if (v1 != null) {
-			MetaType type = v1.getMetaType();
-			if (type instanceof SimpleMetaType) {
-				SimpleValue simple = (SimpleValue) v1;
-				return Boolean.valueOf(simple.getValue().toString());
-			}
-			throw new Exception("Failed to convert value to boolean value"); //$NON-NLS-1$
-		}
-		return null;
-	}
-
-	public static Double doubleValue(MetaValue v1) throws Exception {
-		if (v1 != null) {
-			MetaType type = v1.getMetaType();
-			if (type instanceof SimpleMetaType) {
-				SimpleValue simple = (SimpleValue) v1;
-				return Double.valueOf(simple.getValue().toString());
-			}
-			throw new Exception("Failed to convert value to boolean value"); //$NON-NLS-1$
-		}
-		return null;
-	}
-	
-	public static <T> T getSimpleValue(ManagedComponent mc, String prop,
-			Class<T> expectedType) {
-		ManagedProperty mp = mc.getProperty(prop);
-		if (mp != null) {
-			MetaType metaType = mp.getMetaType();
-			if (metaType.isSimple()) {
-				SimpleValue simpleValue = (SimpleValue) mp.getValue();
-				return expectedType.cast((simpleValue != null) ? simpleValue
-						.getValue() : null);
-			} else if (metaType.isEnum()) {
-				EnumValue enumValue = (EnumValue) mp.getValue();
-				return expectedType.cast((enumValue != null) ? enumValue
-						.getValue() : null);
-			}
-			throw new IllegalStateException(prop + " is not a simple type"); //$NON-NLS-1$
-		}
-		return null;
-	}
-
-	public static <T> T getSimpleValue(ManagedCommon mc, String prop,
-			Class<T> expectedType) {
-		ManagedProperty mp = mc.getProperty(prop);
-		if (mp != null) {
-			MetaType metaType = mp.getMetaType();
-			if (metaType.isSimple()) {
-				SimpleValue simpleValue = (SimpleValue) mp.getValue();
-				return expectedType.cast((simpleValue != null) ? simpleValue
-						.getValue() : null);
-			} else if (metaType.isEnum()) {
-				EnumValue enumValue = (EnumValue) mp.getValue();
-				return expectedType.cast((enumValue != null) ? enumValue
-						.getValue() : null);
-			}
-			throw new IllegalArgumentException(prop + " is not a simple type"); //$NON-NLS-1$
-		}
-		return null;
-	}
-
-	public static Map<String, PropertySimple> getCustomProperties(
-			Configuration pluginConfig) {
-		Map<String, PropertySimple> customProperties = new LinkedHashMap<String, PropertySimple>();
-		if (pluginConfig == null)
-			return customProperties;
-		PropertyMap customPropsMap = pluginConfig.getMap("custom-properties"); //$NON-NLS-1$
-		if (customPropsMap != null) {
-			Collection<Property> customProps = customPropsMap.getMap().values();
-			for (Property customProp : customProps) {
-				if (!(customProp instanceof PropertySimple)) {
-					LOG
-							.error("Custom property definitions in plugin configuration must be simple properties - property " //$NON-NLS-1$
-									+ customProp + " is not - ignoring..."); //$NON-NLS-1$
-					continue;
-				}
-				customProperties.put(customProp.getName(),
-						(PropertySimple) customProp);
-			}
-		}
-		return customProperties;
-	}
-
-	public static Configuration convertManagedObjectToConfiguration(
-			Map<String, ManagedProperty> managedProperties,
-			Map<String, PropertySimple> customProps, ResourceType resourceType) {
-		Configuration config = new Configuration();
-		ConfigurationDefinition configDef = resourceType
-				.getResourceConfigurationDefinition();
-		Map<String, PropertyDefinition> propDefs = configDef
-				.getPropertyDefinitions();
-		Set<String> propNames = managedProperties.keySet();
-		for (String propName : propNames) {
-			PropertyDefinition propertyDefinition = propDefs.get(propName);
-			ManagedProperty managedProperty = managedProperties.get(propName);
-			if (propertyDefinition == null) {
-				if (!managedProperty.hasViewUse(ViewUse.STATISTIC))
-					LOG
-							.debug(resourceType
-									+ " does not define a property corresponding to ManagedProperty '" //$NON-NLS-1$
-									+ propName + "'."); //$NON-NLS-1$
-				continue;
-			}
-			if (managedProperty == null) {
-				// This should never happen, but don't let it blow us up.
-				LOG.error("ManagedProperty '" + propName //$NON-NLS-1$
-						+ "' has a null value in the ManagedProperties Map."); //$NON-NLS-1$
-				continue;
-			}
-			MetaValue metaValue = managedProperty.getValue();
-			if (managedProperty.isRemoved() || metaValue == null) {
-				// Don't even add a Property to the Configuration if the
-				// ManagedProperty is flagged as removed or has a
-				// null value.
-				continue;
-			}
-			PropertySimple customProp = customProps.get(propName);
-			PropertyAdapter<Property, PropertyDefinition> propertyAdapter = PropertyAdapterFactory
-					.getCustomPropertyAdapter(customProp);
-			if (propertyAdapter == null)
-				propertyAdapter = PropertyAdapterFactory
-						.getPropertyAdapter(metaValue);
-			if (propertyAdapter == null) {
-				LOG
-						.error("Unable to find a PropertyAdapter for ManagedProperty '" //$NON-NLS-1$
-								+ propName
-								+ "' with MetaType [" //$NON-NLS-1$
-								+ metaValue.getMetaType()
-								+ "] for ResourceType '" //$NON-NLS-1$
-								+ resourceType.getName() + "'."); //$NON-NLS-1$
-				continue; 
-			}
-			Property property = propertyAdapter.convertToProperty(metaValue,
-					propertyDefinition);
-			config.put(property);
-		}
-		return config;
-	}
-
-	public static void convertConfigurationToManagedProperties(
-			Map<String, ManagedProperty> managedProperties,
-			Configuration configuration, ResourceType resourceType) {
-		ConfigurationDefinition configDefinition = resourceType
-				.getResourceConfigurationDefinition();
-		for (ManagedProperty managedProperty : managedProperties.values()) {
-			String propertyName = managedProperty.getName();
-			PropertyDefinition propertyDefinition = configDefinition
-					.get(propertyName);
-			if (propertyDefinition == null) {
-				// The managed property is not defined in the configuration
-				continue;
-			}
-			populateManagedPropertyFromProperty(managedProperty,
-					propertyDefinition, configuration);
-		}
-		return;
-	}
-
-	public static void populateManagedPropertyFromProperty(
-			ManagedProperty managedProperty,
-			PropertyDefinition propertyDefinition, Configuration configuration) {
-		// If the ManagedProperty defines a default value, assume it's more
-		// definitive than any default value that may
-		// have been defined in the plugin descriptor, and update the
-		// PropertyDefinition to use that as its default
-		// value.
-		MetaValue defaultValue = managedProperty.getDefaultValue();
-		if (defaultValue != null)
-			updateDefaultValueOnPropertyDefinition(propertyDefinition,
-					defaultValue);
-		MetaValue metaValue = managedProperty.getValue();
-		PropertyAdapter propertyAdapter = null;
-		if (metaValue != null) {
-			LOG.trace("Populating existing MetaValue of type " //$NON-NLS-1$
-					+ metaValue.getMetaType() + " from Teiid property " //$NON-NLS-1$
-					+ propertyDefinition.getName() + " with definition " //$NON-NLS-1$
-					+ propertyDefinition + "..."); //$NON-NLS-1$
-			propertyAdapter = PropertyAdapterFactory
-					.getPropertyAdapter(metaValue);
-
-			propertyAdapter.populateMetaValueFromProperty(configuration
-					.getSimple(propertyDefinition.getName()), metaValue,
-					propertyDefinition);
-			managedProperty.setValue(metaValue);
-		} else {
-			MetaType metaType = managedProperty.getMetaType();
-			if (propertyAdapter == null)
-				propertyAdapter = PropertyAdapterFactory
-						.getPropertyAdapter(metaType);
-			LOG.trace("Converting property " + propertyDefinition.getName() //$NON-NLS-1$
-					+ " with definition " + propertyDefinition //$NON-NLS-1$
-					+ " to MetaValue of type " + metaType + "..."); //$NON-NLS-1$ //$NON-NLS-2$
-			metaValue = propertyAdapter.convertToMetaValue(configuration
-					.getSimple(propertyDefinition.getName()),
-					propertyDefinition, metaType);
-			managedProperty.setValue(metaValue);
-		}
-
-	}
-
-	private static void updateDefaultValueOnPropertyDefinition(
-			PropertyDefinition propertyDefinition,
-			@NotNull MetaValue defaultValue) {
-		if (!(propertyDefinition instanceof PropertyDefinitionSimple)) {
-			LOG
-					.debug("Cannot update default value on non-simple property definition " //$NON-NLS-1$
-							+ propertyDefinition
-							+ "(default value is " //$NON-NLS-1$
-							+ defaultValue + ")."); //$NON-NLS-1$
-			return;
-		}
-		MetaType metaType = defaultValue.getMetaType();
-		if (!metaType.isSimple() && !metaType.isEnum()) {
-			LOG.debug("Cannot update default value on " + propertyDefinition //$NON-NLS-1$
-					+ ", because default value's type (" + metaType //$NON-NLS-1$
-					+ ") is not simple or enum."); //$NON-NLS-1$
-			return;
-		}
-		PropertyDefinitionSimple propertyDefinitionSimple = (PropertyDefinitionSimple) propertyDefinition;
-		if (metaType.isSimple()) {
-			SimpleValue defaultSimpleValue = (SimpleValue) defaultValue;
-			Serializable value = defaultSimpleValue.getValue();
-			propertyDefinitionSimple.setDefaultValue((value != null) ? value
-					.toString() : null);
-		} else { // defaultValueMetaType.isEnum()
-			EnumValue defaultEnumValue = (EnumValue) defaultValue;
-			Serializable value = defaultEnumValue.getValue();
-			propertyDefinitionSimple.setDefaultValue((value != null) ? value
-					.toString() : null);
-		}
-	}
-
-	public static MetaType convertPropertyDefinitionToMetaType(
-			PropertyDefinition propDef) {
-		MetaType memberMetaType;
-		if (propDef instanceof PropertyDefinitionSimple) {
-			PropertySimpleType propSimpleType = ((PropertyDefinitionSimple) propDef)
-					.getType();
-			memberMetaType = convertPropertySimpleTypeToSimpleMetaType(propSimpleType);
-		} else if (propDef instanceof PropertyDefinitionList) {
-			// TODO (very low priority, since lists of lists are not going to be
-			// at all common)
-			memberMetaType = null;
-		} else if (propDef instanceof PropertyDefinitionMap) {
-			Map<String, PropertyDefinition> memberPropDefs = ((PropertyDefinitionMap) propDef)
-					.getPropertyDefinitions();
-			if (memberPropDefs.isEmpty())
-				throw new IllegalStateException(
-						"PropertyDefinitionMap doesn't contain any member PropertyDefinitions."); //$NON-NLS-1$
-			// NOTE: We assume member prop defs are all of the same type, since
-			// for MapCompositeMetaTypes, they have to be.
-			PropertyDefinition mapMemberPropDef = memberPropDefs.values()
-					.iterator().next();
-			MetaType mapMemberMetaType = convertPropertyDefinitionToMetaType(mapMemberPropDef);
-			memberMetaType = new MapCompositeMetaType(mapMemberMetaType);
-		} else {
-			throw new IllegalStateException(
-					"List member PropertyDefinition has unknown type: " //$NON-NLS-1$
-							+ propDef.getClass().getName());
-		}
-		return memberMetaType;
-	}
-
-	private static MetaType convertPropertySimpleTypeToSimpleMetaType(
-			PropertySimpleType memberSimpleType) {
-		MetaType memberMetaType;
-		Class memberClass;
-		switch (memberSimpleType) {
-		case BOOLEAN:
-			memberClass = Boolean.class;
-			break;
-		case INTEGER:
-			memberClass = Integer.class;
-			break;
-		case LONG:
-			memberClass = Long.class;
-			break;
-		case FLOAT:
-			memberClass = Float.class;
-			break;
-		case DOUBLE:
-			memberClass = Double.class;
-			break;
-		default:
-			memberClass = String.class;
-			break;
-		}
-		memberMetaType = SimpleMetaType.resolve(memberClass.getName());
-		return memberMetaType;
-	}
-
-	public static SimpleValue wrap(MetaType type, String value)
-			throws Exception {
-		if (type instanceof SimpleMetaType) {
-			SimpleMetaType st = (SimpleMetaType) type;
-
-			if (SimpleMetaType.BIGDECIMAL.equals(st)) {
-				return new SimpleValueSupport(st, new BigDecimal(value));
-			} else if (SimpleMetaType.BIGINTEGER.equals(st)) {
-				return new SimpleValueSupport(st, new BigInteger(value));
-			} else if (SimpleMetaType.BOOLEAN.equals(st)) {
-				return new SimpleValueSupport(st, Boolean.valueOf(value));
-			} else if (SimpleMetaType.BOOLEAN_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Boolean.valueOf(value)
-						.booleanValue());
-			} else if (SimpleMetaType.BYTE.equals(st)) {
-				return new SimpleValueSupport(st, new Byte(value.getBytes()[0]));
-			} else if (SimpleMetaType.BYTE_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, value.getBytes()[0]);
-			} else if (SimpleMetaType.CHARACTER.equals(st)) {
-				return new SimpleValueSupport(st,
-						new Character(value.charAt(0)));
-			} else if (SimpleMetaType.CHARACTER_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, value.charAt(0));
-			} else if (SimpleMetaType.DATE.equals(st)) {
-				try {
-					return new SimpleValueSupport(st, SimpleDateFormat
-							.getInstance().parse(value));
-				} catch (ParseException e) {
-					throw new Exception(
-							"Failed to convert value to SimpleValue", e); //$NON-NLS-1$
-				}
-			} else if (SimpleMetaType.DOUBLE.equals(st)) {
-				return new SimpleValueSupport(st, Double.valueOf(value));
-			} else if (SimpleMetaType.DOUBLE_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Double.parseDouble(value));
-			} else if (SimpleMetaType.FLOAT.equals(st)) {
-				return new SimpleValueSupport(st, Float.parseFloat(value));
-			} else if (SimpleMetaType.FLOAT_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Float.valueOf(value));
-			} else if (SimpleMetaType.INTEGER.equals(st)) {
-				return new SimpleValueSupport(st, Integer.valueOf(value));
-			} else if (SimpleMetaType.INTEGER_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Integer.parseInt(value));
-			} else if (SimpleMetaType.LONG.equals(st)) {
-				return new SimpleValueSupport(st, Long.valueOf(value));
-			} else if (SimpleMetaType.LONG_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Long.parseLong(value));
-			} else if (SimpleMetaType.SHORT.equals(st)) {
-				return new SimpleValueSupport(st, Short.valueOf(value));
-			} else if (SimpleMetaType.SHORT_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Short.parseShort(value));
-			} else if (SimpleMetaType.STRING.equals(st)) {
-				return new SimpleValueSupport(st, value);
-			}
-		}
-		throw new Exception("Failed to convert value to SimpleValue"); //$NON-NLS-1$
-	}
-
-}

Copied: tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java (from rev 2707, branches/7.2.x/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,603 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.rhq.plugin.util;
+
+import java.io.File;
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+
+import javax.naming.NamingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.deployers.spi.management.KnownDeploymentTypes;
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.deployers.spi.management.deploy.DeploymentManager;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedCommon;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedDeployment;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.api.annotation.ViewUse;
+import org.jboss.metatype.api.types.MapCompositeMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.EnumValue;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.jboss.profileservice.spi.ProfileService;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
+import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
+import org.rhq.core.domain.configuration.definition.PropertySimpleType;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.rhq.plugin.TranslatorComponent;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
+
+import com.sun.istack.NotNull;
+
+public class ProfileServiceUtil {
+
+	protected final static Log LOG = LogFactory
+			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY); 
+	private static ComponentType DQPTYPE = new ComponentType("teiid", "dqp"); //$NON-NLS-1$ //$NON-NLS-2$
+	private static String DQPNAME = "RuntimeEngineDeployer"; //$NON-NLS-1$
+	private static String BUFFERSERVICE = "BufferService"; //$NON-NLS-1$
+	private static final Map<String, ComponentType> COMPONENT_TYPE_CACHE = new HashMap<String, ComponentType>();
+	
+	protected static final String PLUGIN = "ProfileService"; //$NON-NLS-1$
+
+	public static ComponentType getComponentType(
+			@NotNull ResourceType resourceType) {
+		String resourceTypeName = resourceType.getName();
+		if (COMPONENT_TYPE_CACHE.containsKey(resourceTypeName))
+			return COMPONENT_TYPE_CACHE.get(resourceTypeName);
+		Configuration defaultPluginConfig = getDefaultPluginConfiguration(resourceType);
+		String type = defaultPluginConfig.getSimpleValue(
+				TranslatorComponent.Config.COMPONENT_TYPE, null);
+		if (type == null || type.equals("")) //$NON-NLS-1$
+			throw new IllegalStateException(
+					"Required plugin configuration property '" //$NON-NLS-1$
+							+ TranslatorComponent.Config.COMPONENT_TYPE
+							+ "' is not defined in default template."); //$NON-NLS-1$
+		String subtype = defaultPluginConfig.getSimpleValue(
+				TranslatorComponent.Config.COMPONENT_SUBTYPE, null);
+		if (subtype == null || subtype.equals("")) //$NON-NLS-1$
+			throw new IllegalStateException(
+					"Required plugin configuration property '" //$NON-NLS-1$
+							+ TranslatorComponent.Config.COMPONENT_SUBTYPE 
+							+ "' is not defined in default template."); //$NON-NLS-1$
+		ComponentType componentType = new ComponentType(type, subtype);
+		COMPONENT_TYPE_CACHE.put(resourceTypeName, componentType);
+		return componentType;
+	}
+
+	private static Configuration getDefaultPluginConfiguration(
+			ResourceType resourceType) {
+		ConfigurationTemplate pluginConfigDefaultTemplate = resourceType
+				.getPluginConfigurationDefinition().getDefaultTemplate();
+		return (pluginConfigDefaultTemplate != null) ? pluginConfigDefaultTemplate
+				.createConfiguration()
+				: new Configuration();
+	}
+
+	/**
+	 * @param name
+	 * @param componentType
+	 * @return
+	 */
+	public static boolean isManagedComponent(
+			ProfileServiceConnection connection, String name,
+			ComponentType componentType) {
+		boolean isDeployed = false;
+		if (name != null) {
+			try {
+				ManagedComponent component = getManagedComponent(connection,
+						componentType, name);
+				if (component != null)
+					isDeployed = true;
+			} catch (Exception e) {
+				// Setting it to true to be safe than sorry, since there might
+				// be a component
+				// already deployed in the AS.
+				isDeployed = true;
+			}
+		}
+		return isDeployed;
+	}
+
+	/**
+	 * Get the passed in {@link ManagedComponent}
+	 * 
+	 * @return {@link ManagedComponent}
+	 * @throws NamingException
+	 * @throws Exception
+	 */
+	public static ManagedComponent getManagedComponent(
+			ProfileServiceConnection connection, ComponentType componentType,
+			String componentName) throws NamingException, Exception {
+		ManagedComponent mc = connection.getManagementView().getComponent(
+				componentName, componentType);
+
+		return mc;
+	}
+
+	/**
+	 * Get the {@link ManagedComponent} for the {@link ComponentType} and sub
+	 * type.
+	 * 
+	 * @return Set of {@link ManagedComponent}s
+	 * @throws NamingException
+	 *             , Exception
+	 * @throws Exception
+	 */
+	public static Set<ManagedComponent> getManagedComponents(ProfileServiceConnection connection,
+			ComponentType componentType) throws NamingException, Exception {
+		
+		Set<ManagedComponent> mcSet = connection.getManagementView().getComponentsForType(componentType);
+
+		return mcSet;
+	}
+
+	/**
+	 * @param {@link ManagementView}
+	 * @return
+	 */
+	public static ManagementView getManagementView(ProfileService ps,
+			boolean load) {
+		ManagementView mv = ps.getViewManager();
+		if (load) {
+			mv.load();
+		}
+		return mv;
+	}
+
+	/**
+	 * Get the {@link DeploymentManager} from the ProfileService
+	 * 
+	 * @return DeploymentManager
+	 * @throws NamingException
+	 * @throws Exception
+	 */
+	public static DeploymentManager getDeploymentManager(ProfileServiceConnection connection)
+			throws NamingException, Exception {
+
+		return connection.getDeploymentManager();
+	}
+
+	/**
+	 * @return {@link File}
+	 * @throws NamingException
+	 *             , Exception
+	 */
+	public static File getDeployDirectory(ProfileServiceConnection connection) throws NamingException, Exception {
+		Set<ManagedDeployment> warDeployments;
+		try {
+			warDeployments = connection.getManagementView()
+					.getDeploymentsForType(KnownDeploymentTypes.JavaEEWebApplication
+							.getType());
+		} catch (Exception e) {
+			throw new IllegalStateException(e);
+		}
+		ManagedDeployment standaloneWarDeployment = null;
+		for (ManagedDeployment warDeployment : warDeployments) {
+			if (warDeployment.getParent() == null) {
+				standaloneWarDeployment = warDeployment;
+				break;
+			}
+		}
+		if (standaloneWarDeployment == null)
+			// This could happen if no standalone WARs, including the admin
+			// console WAR, have been fully deployed yet.
+			return null;
+		URL warUrl;
+		try {
+			warUrl = new URL(standaloneWarDeployment.getName());
+		} catch (MalformedURLException e) {
+			throw new IllegalStateException(e);
+		}
+		File warFile = new File(warUrl.getPath());
+		File deployDir = warFile.getParentFile();
+		return deployDir;
+	}
+
+	public static ManagedComponent getRuntimeEngineDeployer(
+			ProfileServiceConnection connection) throws NamingException,
+			Exception {
+
+		return getManagedComponent(connection, DQPTYPE, DQPNAME);
+	}
+	
+	public static ManagedComponent getBufferService(
+			ProfileServiceConnection connection) throws NamingException,
+			Exception {
+
+		return getManagedComponent(connection, DQPTYPE, BUFFERSERVICE);
+	}
+
+	public static String stringValue(MetaValue v1) throws Exception {
+		if (v1 != null) {
+			MetaType type = v1.getMetaType();
+			if (type instanceof SimpleMetaType) {
+				SimpleValue simple = (SimpleValue) v1;
+				return simple.getValue().toString();
+			}
+			throw new Exception("Failed to convert value to string value"); //$NON-NLS-1$
+		}
+		return null;
+	}
+
+	public static Boolean booleanValue(MetaValue v1) throws Exception {
+		if (v1 != null) {
+			MetaType type = v1.getMetaType();
+			if (type instanceof SimpleMetaType) {
+				SimpleValue simple = (SimpleValue) v1;
+				return Boolean.valueOf(simple.getValue().toString());
+			}
+			throw new Exception("Failed to convert value to boolean value"); //$NON-NLS-1$
+		}
+		return null;
+	}
+
+	public static Double doubleValue(MetaValue v1) throws Exception {
+		if (v1 != null) {
+			MetaType type = v1.getMetaType();
+			if (type instanceof SimpleMetaType) {
+				SimpleValue simple = (SimpleValue) v1;
+				return Double.valueOf(simple.getValue().toString());
+			}
+			throw new Exception("Failed to convert value to boolean value"); //$NON-NLS-1$
+		}
+		return null;
+	}
+	
+	public static <T> T getSimpleValue(ManagedComponent mc, String prop,
+			Class<T> expectedType) {
+		ManagedProperty mp = mc.getProperty(prop);
+		if (mp != null) {
+			MetaType metaType = mp.getMetaType();
+			if (metaType.isSimple()) {
+				SimpleValue simpleValue = (SimpleValue) mp.getValue();
+				return expectedType.cast((simpleValue != null) ? simpleValue
+						.getValue() : null);
+			} else if (metaType.isEnum()) {
+				EnumValue enumValue = (EnumValue) mp.getValue();
+				return expectedType.cast((enumValue != null) ? enumValue
+						.getValue() : null);
+			}
+			throw new IllegalStateException(prop + " is not a simple type"); //$NON-NLS-1$
+		}
+		return null;
+	}
+
+	public static <T> T getSimpleValue(ManagedCommon mc, String prop,
+			Class<T> expectedType) {
+		ManagedProperty mp = mc.getProperty(prop);
+		if (mp != null) {
+			MetaType metaType = mp.getMetaType();
+			if (metaType.isSimple()) {
+				SimpleValue simpleValue = (SimpleValue) mp.getValue();
+				return expectedType.cast((simpleValue != null) ? simpleValue
+						.getValue() : null);
+			} else if (metaType.isEnum()) {
+				EnumValue enumValue = (EnumValue) mp.getValue();
+				return expectedType.cast((enumValue != null) ? enumValue
+						.getValue() : null);
+			}
+			throw new IllegalArgumentException(prop + " is not a simple type"); //$NON-NLS-1$
+		}
+		return null;
+	}
+
+	public static Map<String, PropertySimple> getCustomProperties(
+			Configuration pluginConfig) {
+		Map<String, PropertySimple> customProperties = new LinkedHashMap<String, PropertySimple>();
+		if (pluginConfig == null)
+			return customProperties;
+		PropertyMap customPropsMap = pluginConfig.getMap("custom-properties"); //$NON-NLS-1$
+		if (customPropsMap != null) {
+			Collection<Property> customProps = customPropsMap.getMap().values();
+			for (Property customProp : customProps) {
+				if (!(customProp instanceof PropertySimple)) {
+					LOG
+							.error("Custom property definitions in plugin configuration must be simple properties - property " //$NON-NLS-1$
+									+ customProp + " is not - ignoring..."); //$NON-NLS-1$
+					continue;
+				}
+				customProperties.put(customProp.getName(),
+						(PropertySimple) customProp);
+			}
+		}
+		return customProperties;
+	}
+
+	public static Configuration convertManagedObjectToConfiguration(
+			Map<String, ManagedProperty> managedProperties,
+			Map<String, PropertySimple> customProps, ResourceType resourceType) {
+		Configuration config = new Configuration();
+		ConfigurationDefinition configDef = resourceType
+				.getResourceConfigurationDefinition();
+		Map<String, PropertyDefinition> propDefs = configDef
+				.getPropertyDefinitions();
+		Set<String> propNames = managedProperties.keySet();
+		for (String propName : propNames) {
+			PropertyDefinition propertyDefinition = propDefs.get(propName);
+			ManagedProperty managedProperty = managedProperties.get(propName);
+			if (propertyDefinition == null) {
+				if (!managedProperty.hasViewUse(ViewUse.STATISTIC))
+					LOG
+							.debug(resourceType
+									+ " does not define a property corresponding to ManagedProperty '" //$NON-NLS-1$
+									+ propName + "'."); //$NON-NLS-1$
+				continue;
+			}
+			if (managedProperty == null) {
+				// This should never happen, but don't let it blow us up.
+				LOG.error("ManagedProperty '" + propName //$NON-NLS-1$
+						+ "' has a null value in the ManagedProperties Map."); //$NON-NLS-1$
+				continue;
+			}
+			MetaValue metaValue = managedProperty.getValue();
+			if (managedProperty.isRemoved() || metaValue == null) {
+				// Don't even add a Property to the Configuration if the
+				// ManagedProperty is flagged as removed or has a
+				// null value.
+				continue;
+			}
+			PropertySimple customProp = customProps.get(propName);
+			PropertyAdapter<Property, PropertyDefinition> propertyAdapter = PropertyAdapterFactory
+					.getCustomPropertyAdapter(customProp);
+			if (propertyAdapter == null)
+				propertyAdapter = PropertyAdapterFactory
+						.getPropertyAdapter(metaValue);
+			if (propertyAdapter == null) {
+				LOG
+						.error("Unable to find a PropertyAdapter for ManagedProperty '" //$NON-NLS-1$
+								+ propName
+								+ "' with MetaType [" //$NON-NLS-1$
+								+ metaValue.getMetaType()
+								+ "] for ResourceType '" //$NON-NLS-1$
+								+ resourceType.getName() + "'."); //$NON-NLS-1$
+				continue; 
+			}
+			Property property = propertyAdapter.convertToProperty(metaValue,
+					propertyDefinition);
+			config.put(property);
+		}
+		return config;
+	}
+
+	public static void convertConfigurationToManagedProperties(Map<String, ManagedProperty> managedProperties, Configuration configuration, ResourceType resourceType, String prefix) {
+		ConfigurationDefinition configDefinition = resourceType.getResourceConfigurationDefinition();
+		for (ManagedProperty managedProperty : managedProperties.values()) {
+			String propertyName = managedProperty.getName();
+			if (prefix != null) {
+				propertyName = prefix + "." + propertyName; //$NON-NLS-1$
+			}
+			PropertyDefinition propertyDefinition = configDefinition.get(propertyName);
+			if (propertyDefinition == null) {
+				// The managed property is not defined in the configuration
+				continue;
+			}
+			populateManagedPropertyFromProperty(managedProperty,propertyDefinition, configuration);
+		}
+		return;
+	}
+
+	public static void populateManagedPropertyFromProperty(ManagedProperty managedProperty, PropertyDefinition propertyDefinition, Configuration configuration) {
+		// If the ManagedProperty defines a default value, assume it's more
+		// definitive than any default value that may
+		// have been defined in the plugin descriptor, and update the
+		// PropertyDefinition to use that as its default
+		// value.
+		MetaValue defaultValue = managedProperty.getDefaultValue();
+		if (defaultValue != null) {
+			updateDefaultValueOnPropertyDefinition(propertyDefinition,defaultValue);
+		}
+		MetaValue metaValue = managedProperty.getValue();
+		PropertyAdapter propertyAdapter = null;
+		if (metaValue != null) {
+			LOG.trace("Populating existing MetaValue of type " //$NON-NLS-1$
+					+ metaValue.getMetaType() + " from Teiid property " //$NON-NLS-1$
+					+ propertyDefinition.getName() + " with definition " //$NON-NLS-1$
+					+ propertyDefinition + "..."); //$NON-NLS-1$
+			propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(metaValue);
+
+			propertyAdapter.populateMetaValueFromProperty(configuration.getSimple(propertyDefinition.getName()), metaValue, propertyDefinition);
+			managedProperty.setValue(metaValue);
+		} else {
+			MetaType metaType = managedProperty.getMetaType();
+			propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(metaType);
+			LOG.trace("Converting property " + propertyDefinition.getName() 	+ " with definition " + propertyDefinition 	+ " to MetaValue of type " + metaType + "..."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			metaValue = propertyAdapter.convertToMetaValue(configuration.getSimple(propertyDefinition.getName()),propertyDefinition, metaType);
+			managedProperty.setValue(metaValue);
+		}
+
+	}
+
+	private static void updateDefaultValueOnPropertyDefinition(
+			PropertyDefinition propertyDefinition,
+			@NotNull MetaValue defaultValue) {
+		if (!(propertyDefinition instanceof PropertyDefinitionSimple)) {
+			LOG.debug("Cannot update default value on non-simple property definition " //$NON-NLS-1$
+							+ propertyDefinition + "(default value is " //$NON-NLS-1$
+							+ defaultValue + ")."); //$NON-NLS-1$
+			return;
+		}
+		MetaType metaType = defaultValue.getMetaType();
+		if (!metaType.isSimple() && !metaType.isEnum()) {
+			LOG.debug("Cannot update default value on " + propertyDefinition //$NON-NLS-1$
+					+ ", because default value's type (" + metaType //$NON-NLS-1$
+					+ ") is not simple or enum."); //$NON-NLS-1$
+			return;
+		}
+		PropertyDefinitionSimple propertyDefinitionSimple = (PropertyDefinitionSimple) propertyDefinition;
+		if (metaType.isSimple()) {
+			SimpleValue defaultSimpleValue = (SimpleValue) defaultValue;
+			Serializable value = defaultSimpleValue.getValue();
+			propertyDefinitionSimple.setDefaultValue((value != null) ? value.toString() : null);
+		} else { // defaultValueMetaType.isEnum()
+			EnumValue defaultEnumValue = (EnumValue) defaultValue;
+			Serializable value = defaultEnumValue.getValue();
+			propertyDefinitionSimple.setDefaultValue((value != null) ? value.toString() : null);
+		}
+	}
+
+	public static MetaType convertPropertyDefinitionToMetaType(
+			PropertyDefinition propDef) {
+		MetaType memberMetaType;
+		if (propDef instanceof PropertyDefinitionSimple) {
+			PropertySimpleType propSimpleType = ((PropertyDefinitionSimple) propDef)
+					.getType();
+			memberMetaType = convertPropertySimpleTypeToSimpleMetaType(propSimpleType);
+		} else if (propDef instanceof PropertyDefinitionList) {
+			// TODO (very low priority, since lists of lists are not going to be
+			// at all common)
+			memberMetaType = null;
+		} else if (propDef instanceof PropertyDefinitionMap) {
+			Map<String, PropertyDefinition> memberPropDefs = ((PropertyDefinitionMap) propDef)
+					.getPropertyDefinitions();
+			if (memberPropDefs.isEmpty())
+				throw new IllegalStateException(
+						"PropertyDefinitionMap doesn't contain any member PropertyDefinitions."); //$NON-NLS-1$
+			// NOTE: We assume member prop defs are all of the same type, since
+			// for MapCompositeMetaTypes, they have to be.
+			PropertyDefinition mapMemberPropDef = memberPropDefs.values()
+					.iterator().next();
+			MetaType mapMemberMetaType = convertPropertyDefinitionToMetaType(mapMemberPropDef);
+			memberMetaType = new MapCompositeMetaType(mapMemberMetaType);
+		} else {
+			throw new IllegalStateException(
+					"List member PropertyDefinition has unknown type: " //$NON-NLS-1$
+							+ propDef.getClass().getName());
+		}
+		return memberMetaType;
+	}
+
+	private static MetaType convertPropertySimpleTypeToSimpleMetaType(
+			PropertySimpleType memberSimpleType) {
+		MetaType memberMetaType;
+		Class memberClass;
+		switch (memberSimpleType) {
+		case BOOLEAN:
+			memberClass = Boolean.class;
+			break;
+		case INTEGER:
+			memberClass = Integer.class;
+			break;
+		case LONG:
+			memberClass = Long.class;
+			break;
+		case FLOAT:
+			memberClass = Float.class;
+			break;
+		case DOUBLE:
+			memberClass = Double.class;
+			break;
+		default:
+			memberClass = String.class;
+			break;
+		}
+		memberMetaType = SimpleMetaType.resolve(memberClass.getName());
+		return memberMetaType;
+	}
+
+	public static SimpleValue wrap(MetaType type, String value)
+			throws Exception {
+		if (type instanceof SimpleMetaType) {
+			SimpleMetaType st = (SimpleMetaType) type;
+
+			if (SimpleMetaType.BIGDECIMAL.equals(st)) {
+				return new SimpleValueSupport(st, new BigDecimal(value));
+			} else if (SimpleMetaType.BIGINTEGER.equals(st)) {
+				return new SimpleValueSupport(st, new BigInteger(value));
+			} else if (SimpleMetaType.BOOLEAN.equals(st)) {
+				return new SimpleValueSupport(st, Boolean.valueOf(value));
+			} else if (SimpleMetaType.BOOLEAN_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Boolean.valueOf(value)
+						.booleanValue());
+			} else if (SimpleMetaType.BYTE.equals(st)) {
+				return new SimpleValueSupport(st, new Byte(value.getBytes()[0]));
+			} else if (SimpleMetaType.BYTE_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, value.getBytes()[0]);
+			} else if (SimpleMetaType.CHARACTER.equals(st)) {
+				return new SimpleValueSupport(st,
+						new Character(value.charAt(0)));
+			} else if (SimpleMetaType.CHARACTER_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, value.charAt(0));
+			} else if (SimpleMetaType.DATE.equals(st)) {
+				try {
+					return new SimpleValueSupport(st, SimpleDateFormat
+							.getInstance().parse(value));
+				} catch (ParseException e) {
+					throw new Exception(
+							"Failed to convert value to SimpleValue", e); //$NON-NLS-1$
+				}
+			} else if (SimpleMetaType.DOUBLE.equals(st)) {
+				return new SimpleValueSupport(st, Double.valueOf(value));
+			} else if (SimpleMetaType.DOUBLE_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Double.parseDouble(value));
+			} else if (SimpleMetaType.FLOAT.equals(st)) {
+				return new SimpleValueSupport(st, Float.parseFloat(value));
+			} else if (SimpleMetaType.FLOAT_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Float.valueOf(value));
+			} else if (SimpleMetaType.INTEGER.equals(st)) {
+				return new SimpleValueSupport(st, Integer.valueOf(value));
+			} else if (SimpleMetaType.INTEGER_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Integer.parseInt(value));
+			} else if (SimpleMetaType.LONG.equals(st)) {
+				return new SimpleValueSupport(st, Long.valueOf(value));
+			} else if (SimpleMetaType.LONG_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Long.parseLong(value));
+			} else if (SimpleMetaType.SHORT.equals(st)) {
+				return new SimpleValueSupport(st, Short.valueOf(value));
+			} else if (SimpleMetaType.SHORT_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Short.parseShort(value));
+			} else if (SimpleMetaType.STRING.equals(st)) {
+				return new SimpleValueSupport(st, value);
+			}
+		}
+		throw new Exception("Failed to convert value to SimpleValue"); //$NON-NLS-1$
+	}
+
+}

Deleted: tags/teiid-parent-7.2.0.Final/console/src/main/resources/META-INF/rhq-plugin.xml
===================================================================
--- branches/7.2.x/console/src/main/resources/META-INF/rhq-plugin.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/resources/META-INF/rhq-plugin.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,706 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-
-	<!--
-		* JBoss, Home of Professional Open Source. * See the COPYRIGHT.txt
-		file distributed with this work for information * regarding copyright
-		ownership. Some portions may be licensed * to Red Hat, Inc. under one
-		or more contributor license agreements. * * This library is free of
-		the GNU Lesser General Public * License as published by the Free
-		Software Foundation; either * version 2.1 of the License, or (at your
-		option) any later version. * * This library is distributed in the hope
-		that it will be useful, * but WITHOUT ANY WARRANTY; without even the
-		implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR
-		PURPOSE. See the GNU * Lesser General Public License for more details.
-		* * You should have received a copy of the GNU Lesser General Public *
-		License along with this library; if not, write to the Free Software *
-		Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
-		02110-1301 USA. */
-	-->
-	
-	<!DOCTYPE plugin [
-
-<!ENTITY managedObjectMetrics '
-    <metric property="runState" displayType="summary"
-            defaultOn="true" defaultInterval="30000" dataType="trait" category="performance"/>
-'>
-
-<!ENTITY translatorConfiguration '
-
-    <c:list-property name="translatorList" description="Properties for this translator"
-						readOnly="true">
-						<c:simple-property name="name" displayName="Name"
-							description="Name of the translator" />
-						<c:simple-property name="execution-factory-class" displayName="execution-factory-class"
-							description="Connector Class" />	
-						 <c:list-property name="translatorList" description="Properties for this translator" readOnly="true">
-						<c:map-property name="translator-properties" >
-							<c:simple-property name="name" displayName="Name"
-								description="Name of this property" readOnly="true" />
-							<c:simple-property name="value" displayName="Value"
-								description="Value of this property" />
-							<c:simple-property name="description" displayName="Description"
-								description="Description of this property" />
-						</c:map-property>						
-	</c:list-property>
-	
-'>			
-		
-<!ENTITY accessTranslatorConfiguration '
-	<resource-configuration>
-    <c:list-property name="translatorList" description="Properties for this translator"
-						readOnly="true">
-						<c:map-property name="translatorMap">
-							<c:simple-property name="name" displayName="Name"
-								description="Name of this property" readOnly="true" />
-							<c:simple-property name="value" displayName="Value"
-								description="Value of this property" readOnly="true" />
-							<c:simple-property name="description" displayName="Description"
-								description="Description of this property" readOnly="true" />
-						</c:map-property>
-	</c:list-property>
-	</resource-configuration>    
-    
-'>					
-
-
-]>
-
-	<!--
-		############################################# END OF XML ENTITIES
-		###############################################
-	-->
-
-
-
-<plugin name="TeiidPlugin" displayName="Teiid Plugin" package="org.teiid.rhq.plugin"
-	version="2.0.0" description="Supports management and monitoring of JBoss Teiid"
-	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:xmlns:rhq-plugin"
-	xmlns:c="urn:xmlns:rhq-configuration">
-
-	<depends plugin="JBossAS5" useClasses="true" />
-
-	<server name="Data Services" description="Teiid Data Services"
-		class="PlatformComponent" discovery="PlatformDiscoveryComponent"
-		singleton="true">
-
-		<runs-inside>
-			<parent-resource-type name="JBossAS Server"
-				plugin="JBossAS5" />
-		</runs-inside>
-
-		<operation name="getLongRunningRequests" displayName="View current long running queries"
-			description="List current queries executing against the Teiid System that have surpassed the long running query threshhold">
-			<results>
-				<c:list-property name="list">
-					<c:map-property name="map">
-						<c:simple-property displayName="Session ID"
-							name="getSessionId" type="string"
-							description="The name of the resource whose availability is being reported" />
-						<c:simple-property displayName="Request ID"
-							name="getRequestId" type="string" description="The id for the request" />
-						<c:simple-property displayName="SQL String"
-							name="getCommand" type="string" description="The SQL string for this query" />
-						<c:simple-property displayName="Source Request"
-							name="sourceRequest" type="string"
-							description="If false,this is the top level query. If true, this a physical source query." />
-						<c:simple-property displayName="Execution ID"
-							name="getExecutionId" type="string"
-							description="The execution id for this request (if this is a physical source query)" />
-						<c:simple-property displayName="Start Time"
-							name="getCreatedTime" type="string" description="The time this query began" />
-						<c:simple-property displayName="Start Time"
-							name="getProcessingTime" type="string" description="Processing time for this request" />
-						<c:simple-property displayName="Transaction ID"
-							name="getTransactionId" type="string"
-							description="The transaction XID if there is a transaction involved" />
-						<c:simple-property displayName="Node ID" name="getNodeId"
-							type="string" description="The node ID of this query" />
-					</c:map-property>
-				</c:list-property>
-			</results>
-		</operation>
-
-		<operation name="getSessions" displayName="View current sessions"
-			description="Get current sessions connected to the Teiid instance">
-			<results>
-
-				<c:list-property name="list" displayName="Current Sessions"
-					description="Sessions currently connected to the Teiid system"
-					required="false">
-					<c:map-property name="map">
-						<c:simple-property displayName="Session ID"
-							name="getSessionId" type="string" description="The identifier for this session" />
-						<c:simple-property displayName="Application Name"
-							name="getApplicationName" type="string"
-							description="The application associated with Session" />
-						<c:simple-property displayName="Created Time"
-							name="getCreatedTime" type="string" description="When the session was created" />
-						<c:simple-property displayName="Client Host"
-							name="getClientHostName" type="string"
-							description="Host name from where the session created" />
-						<c:simple-property displayName="IP Address"
-							name="getIPAddress" type="string"
-							description="IP address from where this session was created" />
-						<c:simple-property displayName="Last ping time"
-							name="getLastPingTime" type="string" description="Last ping time" />
-						<c:simple-property displayName="User Name" name="getUserName"
-							type="string" description="User associated with this session" />
-						<c:simple-property displayName="VDB Name" name="getVDBName"
-							type="string" description="VDB associated with this session" />
-						<c:simple-property displayName="Security Domain"
-							name="getSecurityDomain" type="string"
-							description="Security Domain that session logged into" />
-					</c:map-property>
-				</c:list-property>
-			</results>
-		</operation>
-
-		<operation name="deployVdbByUrl" displayName="Deploy a VDB via URL"
-			description="Deploy a VDB using a URL">
-			<parameters>
-				<c:simple-property displayName="VDB URL" name="vdbUrl"
-					type="file" required="true" description="The URL of the VDB to deploy" />
-				<c:simple-property displayName="VDB Deploy File Name"
-					name="vdbDeployName" type="string" required="true"
-					description="The deployment file name to use. Must match the VDB Name you are deploying." />
-				<c:simple-property displayName="VDB Version" name="vdbVersion"
-					type="integer" required="false"
-					description="The version to use for the deployed VDB (leave blank for overwrite of version one)" />
-			</parameters>
-		</operation>
-
-
-		<operation name="terminateSession" displayName="Terminate Session"
-			description="Terminate a specified session">
-			<parameters>
-				<c:simple-property displayName="SessionID" name="sessionID"
-					type="long" required="true" description="The ID of the session to terminate" />
-			</parameters>
-		</operation>
-
-
-		<operation name="getRequests" displayName="View current requests"
-			description="Get current requests executing against this Teiid instance">
-			<results>
-
-				<c:list-property name="list" displayName="Current Request"
-					description="Requests currently executing against the Teiid system"
-					required="false">
-					<c:map-property name="map">
-						<c:simple-property displayName="Request ID"
-							name="getRequestId" type="string" description="The request identifier" />
-						<c:simple-property displayName="Session ID"
-							name="getSessionId" type="string" description="Session identifier" />
-						<c:simple-property displayName="Execution ID"
-							name="getExecutionId" type="string" description="Unique Identifier for Request" />
-						<c:simple-property displayName="Created Time"
-							name="getCreatedTime" type="string" description="Time when request submitted" />
-						<c:simple-property displayName="Processing Time"
-							name="getProcessingTime" type="string" description="Processing time for the request" />
-						<c:simple-property displayName="Last ping time"
-							name="getCommand" type="string" description="SQL Command" />
-						<c:simple-property displayName="Connector level request?"
-							name="sourceRequest" type="string"
-							description="True if this is a connector level request" />
-						<c:simple-property displayName="Node ID" name="getNodeId"
-							type="string" description="The node identifier" />
-						<c:simple-property displayName="Tansaction identifier"
-							name="getTransactionId" type="string"
-							description="Transaction XID if a transaction is involved" />
-					</c:map-property>
-				</c:list-property>
-			</results>
-		</operation>
-
-		<operation name="cancelRequest" displayName="Terminate request"
-			description="Terminate the processing of a query and its source queries">
-			<parameters>
-				<c:simple-property displayName="Session ID" name="sessionID"
-					type="long" required="true"
-					description="The ID of the session that the request to cancel is associated with" />
-				<c:simple-property displayName="Request ID" name="requestID"
-					type="long" required="true" description="The ID of the request to cancel" />
-			</parameters>
-		</operation>
-
-		<operation name="getTransactions" displayName="View current transactions"
-			description="Get current transactions executing against this VDB">
-			<results>
-				<c:list-property name="list" displayName="Current Transactions"
-					description="Transactions currently executing against the Teiid system"
-					required="false">
-					<c:map-property name="map">
-						<c:simple-property displayName="Transaction ID"
-							name="getId" type="string"
-							description="The Xid string for GLOBAL transactions or the Transaction id string LOCAL/REQUEST." />
-						<c:simple-property displayName="Session ID"
-							name="getAssociatedSession" type="string"
-							description="Get the session associated with the this transaction. May be null for an unassociated Global transaction." />
-						<c:simple-property displayName="Scope" name="getScope"
-							type="string"
-							description="Get the scope for the transaction.  Will be one of GLOBAL, LOCAL, or REQUEST" />
-						<c:simple-property displayName="Created Time"
-							name="getCreatedTime" type="string" description="The local creation time." />
-					</c:map-property>
-				</c:list-property>
-			</results>
-		</operation>
-
-		<operation name="terminateTransaction" displayName="Terminate Transaction"
-			description="Terminate a specified transaction">
-			<parameters>
-				<c:simple-property displayName="Transaction ID"
-					name="transactionID" type="long" required="true"
-					description="The ID of the transaction to terminate" />
-			</parameters>
-		</operation>
-
-		<metric displayName="Query Count" defaultOn="true" displayType="detail"
-			category="throughput" property="queryCount"
-			description="The number of queries currently active." />
-
-		<metric displayName="Long Running Queries" defaultOn="true"
-			displayType="detail" category="performance" property="longRunningQueries"
-			description="The number of queries that have been running longer than the limit set for queries." />
-
-		<metric displayName="Session Count" defaultOn="true"
-			displayType="detail" category="throughput" property="sessionCount"
-			description="The number of user connections currently active." />
-
-		<metric displayName="Used Buffer Space" defaultOn="true"
-			displayType="detail" category="throughput" property="userBufferSpace"
-			description="The currently used file buffer space in MB." />
-
-		<metric displayName="Prepared Plan Cache Hit Ratio %"
-			defaultOn="true" displayType="detail" category="performance"
-			property="PREPARED_PLAN_CACHE.hitRatio" description="Percentage of positive cache hits" />
-
-		<metric displayName="Prepared Plan Cache Size" defaultOn="true"
-			displayType="detail" category="performance" property="PREPARED_PLAN_CACHE.totalEntries"
-			description="Current number of entries in cache" />
-
-		<metric displayName="Prepared Plan Cache # of Requests"
-			defaultOn="true" displayType="detail" category="performance"
-			property="PREPARED_PLAN_CACHE.requestCount" description="Total number of requests made against cache" />
-
-		<metric displayName="ResultSet Cache Hit Ratio %" defaultOn="true"
-			displayType="detail" category="performance"
-			property="QUERY_SERVICE_RESULT_SET_CACHE.hitRatio" description="Percentage of positive cache hits" />
-
-		<metric displayName="ResultSet Cache Size" defaultOn="true"
-			displayType="detail" category="performance"
-			property="QUERY_SERVICE_RESULT_SET_CACHE.totalEntries" description="Current number of entries in cache" />
-
-		<metric displayName="ResultSet Cache  # of Requests" defaultOn="true"
-			displayType="detail" category="performance"
-			property="QUERY_SERVICE_RESULT_SET_CACHE.requestCount" description="Total number of requests made against cache" />
-
-		<resource-configuration>
-			<c:group name="teiidProperties" displayName="Runtime Engine Properties"
-				hiddenByDefault="false">
-				<c:simple-property name="maxRowsFetchSize"
-					displayName="Max Rows Fetch Size"
-					description="The maximum number of result set cache entries. 0 indicates no limit. (default 1024)"
-					required="false" readOnly="false" />
-				<c:simple-property name="processName" displayName="Process Name"
-					description="Name that uniquely identifies this process" required="false"
-					readOnly="false" />
-				<c:simple-property name="maxThreads" displayName="Max Threads"
-					description="Process pool maximum thread count. (default 64)"
-					required="false" readOnly="false" />
-				<c:simple-property name="timeSliceInMilli"
-					displayName="Time Slice In Milliseconds"
-					description="Query processor time slice, in milliseconds. (default 2000)"
-					required="false" readOnly="false" />
-				<c:simple-property name="lobChunkSizeInKB"
-					displayName="Lob Chunk Size In KB"
-					description="The max lob chunk size in KB transferred to the client for xml, blobs, clobs (default 100KB)"
-					required="false" readOnly="false" />
-				<c:simple-property name="resultSetCacheEnabled"
-					displayName="Result Set Cache Enabled"
-					description="Denotes whether or not result set caching is enabled. (default true)"
-					required="false" readOnly="false" type="boolean" />
-				<c:simple-property name="resultSetCacheMaxEntries"
-					displayName="Result Set Cache Max Entries"
-					description="The maximum number of result set cache entries. -1 indicates no limit. (default 1024)"
-					required="false" readOnly="false" />
-				<c:simple-property name="resultSetCacheMaxEntryAge"
-					displayName="Result Set Cache Max Entry Age"
-					description="The maximum age of a result set cache entry in seconds. -1 indicates no max. (default 7200)"
-					required="false" readOnly="false" />
-				<c:simple-property name="preparedPlanCacheMaxCount"
-					displayName="Prepared Plan Cache Max Count"
-					description="The maximum number of query plans that are cached. Note: this is a memory based cache. (default 250)"
-					required="false" readOnly="false" />
-				<c:simple-property name="activeSessionsCount"
-					displayName="Active Session Count" description="Count of active sessions"
-					required="false" readOnly="false" />
-				<c:simple-property name="queryThresholdInSecs"
-					displayName="Long Running Query Threshold"
-					description="Length of time in seconds before a query is considered long running"
-					required="false" readOnly="false" />
-			</c:group>
-			<c:group name="bufferServiceProperties" displayName="Buffer Service Properties"
-				hiddenByDefault="false">
-				<c:simple-property name="maxBufferSpace"
-					displayName="Max Buffer Space"
-					description="Max file storage space, in MB, to be used for buffer files (default 50G)"
-					required="false" readOnly="false" />
-				<c:simple-property name="processorBatchSize"
-					displayName="Processor Batch Size"
-					description="The max row count of a batch sent internally within the query processor. Should be &lt;= the connectorBatchSize. (default 512)"
-					required="false" readOnly="false" />
-				<c:simple-property name="connectorBatchSize"
-					displayName="Connector Batch Size"
-					description="The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024)"
-					required="false" readOnly="false" />
-				<c:simple-property name="maxProcessingBatchesColumns"
-					displayName="Max Processing Batches Columns"
-					description="The number of batch columns guarenteed to a processing operation.  Set this value lower if the workload typically processes larger numbers of concurrent queries with large intermediate results from operations such as sorting, grouping, etc. (default 128)"
-					required="false" readOnly="false" />
-				<c:simple-property name="maxFileSize" displayName="Max File Size"
-					description="Max file size for buffer files (default 2GB)"
-					required="false" readOnly="false" />
-				<c:simple-property name="maxReserveBatchColumns"
-					displayName="Max Reserve Batch Columns"
-					description="The number of batch columns to allow in memory (default 16384).  This value should be set lower or higher depending on the available memory to Teiid in the VM.  16384 is considered a good default for a dedicated 32-bit VM running Teiid with a 1 gig heap."
-					required="false" readOnly="false" />
-			</c:group>
-			<c:group name="jdbcSocketConfigurationProperties"
-				displayName="Jdbc Socket Configuration Properties" hiddenByDefault="false">
-				<c:simple-property name="portNumber" displayName="Port Number"
-					description="Port Number" required="false" readOnly="false" />
-				<c:simple-property name="sslEnabled" displayName="SSL Enabled"
-					description="SSL enabled" required="false" readOnly="false" type="boolean"
-					default="true" />
-				<c:simple-property name="hostName" displayName="Host Name"
-					description="Host Name" required="false" readOnly="false" />
-				<c:simple-property name="maxSocketThreads"
-					displayName="Max Socket Threads" description="Max NIO threads"
-					required="false" readOnly="false" />
-				<c:simple-property name="inputBufferSize"
-					displayName="Input Buffer Size"
-					description="SO_RCVBUF size, 0 indicates that system default should be used (default 0)"
-					required="false" readOnly="false" />
-				<c:simple-property name="outputBufferSize"
-					displayName="Output Buffer Size"
-					description="SO_SNDBUF size, 0 indicates that system default should be used (default 0)"
-					required="false" readOnly="false" />
-			</c:group>
-			<c:group name="sessionServiceProperties" displayName="Session Service Properties"
-				hiddenByDefault="false">
-				<c:simple-property name="sessionExpirationTimeLimit"
-					displayName="Session Expiration Time Limit"
-					description="Max allowed time before the session is terminated by the system, 0 indicates unlimited (default 0)"
-					required="false" readOnly="false" />
-				<c:simple-property name="sessionMaxLimit"
-					displayName="Session Max Limit"
-					description="Maximum number of sessions allowed by the system (default 5000)"
-					required="false" readOnly="false" />
-			</c:group>
-		</resource-configuration>
-
-		<service name="Virtual Database (VDB)s" description="Teiid Data Services Virtual Databases"
-			class="VDBComponent" discovery="VDBDiscoveryComponent"
-			createDeletePolicy="both" creationDataType="content">
-
-			<operation name="getSessions" displayName="View VDB Sessions"
-				description="Get current sessions currently connected to this VDB">
-				<results>
-
-					<c:list-property name="list" displayName="Current VDB Sessions"
-						description="Sessions currently connected to this VDB" required="false">
-						<c:map-property name="map">
-							<c:simple-property displayName="Session ID"
-								name="getSessionId" type="string" description="The identifier for this session" />
-							<c:simple-property displayName="Application Name"
-								name="getApplicationName" type="string"
-								description="The application associated with Session" />
-							<c:simple-property displayName="Created Time"
-								name="getCreatedTime" type="string" description="When the session was created" />
-							<c:simple-property displayName="Client Host"
-								name="getClientHostName" type="string"
-								description="Host name from where the session created" />
-							<c:simple-property displayName="IP Address"
-								name="getIPAddress" type="string"
-								description="IP address from where this session was created" />
-							<c:simple-property displayName="Last ping time"
-								name="getLastPingTime" type="string" description="Last ping time" />
-							<c:simple-property displayName="User Name"
-								name="getUserName" type="string" description="User associated with this session" />
-							<c:simple-property displayName="Security Domain"
-								name="getSecurityDomain" type="string"
-								description="Security Domain that session logged into" />
-						</c:map-property>
-					</c:list-property>
-				</results>
-			</operation>
-
-			<operation name="getRequestsUsingVDB" displayName="View VDB requests"
-				description="Get current requests executing against this VDB">
-				<results>
-
-					<c:list-property name="list" displayName="Current Request"
-						description="Requests currently executing against the Teiid system"
-						required="false">
-						<c:map-property name="map">
-							<c:simple-property displayName="Request ID"
-								name="getRequestId" type="string" description="The request identifier" />
-							<c:simple-property displayName="Session ID"
-								name="getSessionId" type="string" description="Session identifier" />
-							<c:simple-property displayName="Execution ID"
-								name="getExecutionId" type="string" description="Unique Identifier for Request" />
-							<c:simple-property displayName="Created Time"
-								name="getCreatedTime" type="string" description="Time when request submitted" />
-							<c:simple-property displayName="Processing Time"
-								name="getProcessingTime" type="string" description="Processing time for the request" />
-							<c:simple-property displayName="Last ping time"
-								name="getCommand" type="string" description="SQL Command" />
-							<c:simple-property displayName="Connector level request?"
-								name="sourceRequest" type="string"
-								description="True if this is a connector level request" />
-							<c:simple-property displayName="Node ID" name="getNodeId"
-								type="string" description="The node identifier" />
-							<c:simple-property displayName="Tansaction identifier"
-								name="getTransactionId" type="string"
-								description="Transaction XID if a transaction is involved" />
-						</c:map-property>
-					</c:list-property>
-				</results>
-			</operation>
-
-			<operation name="getMaterializedViews" displayName="List Materialized View Info"
-				description="List any Materialized Views for this VDB">
-
-				<results>
-
-					<c:list-property name="list" displayName="Materialized Views"
-						description="List information related to Materialized Views, if any, for this VDB"
-						required="false">
-						<c:map-property name="map">
-							<c:simple-property displayName="Schema Name"
-								name="schemaName" type="string" description="Name of the schema that is materialized" />
-							<c:simple-property displayName="Name" name="name"
-								type="string" description="Name of the materialized table" />
-							<c:simple-property displayName="Target Schema Name"
-								name="targetSchemaName" type="string" description="Name of the materialized schema" />
-							<c:simple-property displayName="Target Name"
-								name="targetName" type="string" description="Name of target table" />
-							<c:simple-property displayName="Valid"
-								name="valid" type="string" description="Indicates if data in table is valid for use" />
-							<c:simple-property displayName="Current State"
-								name="loadState" type="string" description="Processing time for the request" />
-							<c:simple-property displayName="Last Updated"
-								name="updated" type="integer" description="Last time of data refresh" />
-							<c:simple-property displayName="Cardinality"
-								name="cardinality" type="integer" description="Row count" />
-						</c:map-property>
-					</c:list-property>
-				</results>
-			</operation>
-
-			<operation name="reloadMaterializedView" displayName="Refresh a Materialized View"
-				description="Refresh a given any Materialized View for this VDB">
-				<parameters>
-					<c:simple-property displayName="Materialized View Schema"
-						name="schema" type="string" required="true"
-						description="The schema name of the Materialized View to refresh" />
-					<c:simple-property displayName="Materialized View Name"
-						name="table" type="string" required="true"
-						description="The name of the Materialized View to refresh" />
-					<c:simple-property displayName="Invalidate Current Materialized View Table"
-						name="invalidate" type="boolean" required="true" default="false"
-						description="If yes, will block all queries against the current Materialized View table until data is refreshed." />
-				</parameters>
-
-				<results>
-					<c:simple-property displayName="Result" name="operationResult"
-						type="string" description="Result of refresh" />
-				</results>
-			</operation>
-
-			<metric displayName="Status" defaultOn="true" dataType="trait"
-				displayType="summary" category="availability" property="status"
-				description="The status of this VDB" />
-
-			<metric displayName="Errors" defaultOn="true" dataType="trait"
-				displayType="summary" category="availability" property="errorCount"
-				description="Whether or not errors exist for this VDB" />
-
-			<content name="vdb" displayName="VDB Archive" category="deployable"
-				isCreationType="true">
-			</content>
-
-			<resource-configuration>
-				<c:group name="general" displayName="General"
-					hiddenByDefault="false">
-					<c:simple-property name="name" type="string"
-						description="The Virtual Database Name" required="false" readOnly="true" />
-					<c:simple-property name="version" type="string"
-						description="The Virtual Database Version" required="false"
-						readOnly="true" />
-					<c:simple-property name="description" type="string"
-						description="The Virtual Database Description" required="false"
-						readOnly="true" />
-					<c:simple-property name="status" type="string"
-						description="The Virtual Database Status" required="false"
-						summary="true" readOnly="true">
-						<c:property-options>
-							<c:option value="ACTIVE" name="UP" />
-							<c:option value="INACTIVE" name="DOWN" default="true" />
-						</c:property-options>
-					</c:simple-property>
-					<c:simple-property name="connectionType" type="string"
-						description="Allowable Connections: 1) NONE - disallow new connections 2) BY VERSION - allow connections only if the version is specified or if this is the earliest 'BY VERSION' vdb and there are no vdbs marked as 'ANY' 
-3) ANY - allow connections with or without a version specified. If multiple versions of same VDB are deployed, connect to one specified with ANY, or if there are multiple VDBs with ANY then connect to the latest version with ANY "
-						required="false">
-						<c:property-options>
-							<c:option value="NONE" name="NONE" />
-							<c:option value="BY_VERSION" name="BY VERSION" default="true" />
-							<c:option value="ANY" name="ANY" />
-						</c:property-options>
-					</c:simple-property>
-					<c:simple-property name="url" type="string"
-						description="The Virtual Database URL" required="false" readOnly="true" />
-				</c:group>
-				<c:group name="Translators" displayName="Translators"
-					hiddenByDefault="false">
-					<c:list-property name="translators" displayName="Overrides"
-						readOnly="true" description="The translator overrides for this VDB">
-						<c:map-property name="map"
-							description="Translator Overrides for this VDB">
-							<c:simple-property name="name" displayName="Name"
-								description="Name of this translator instance" required="false"
-								readOnly="true" />
-							<c:simple-property name="type" displayName="Translator type"
-								description="Translator type" required="false" readOnly="true" />
-							<c:simple-property name="propertyName"
-								displayName="Property Name" description="Property Name"
-								required="false" readOnly="true" />
-							<c:simple-property name="propertyValue"
-								displayName="Property Value" description="Property Value"
-								required="false" readOnly="true" />
-						</c:map-property>
-					</c:list-property>
-				</c:group>
-				<c:group name="Models" displayName="Models" hiddenByDefault="false">
-					<c:list-property name="singleSourceModels"
-						readOnly="true" description="The source models for this VDB">
-						<c:map-property name="map" description="Properties for this model">
-							<c:simple-property name="name" displayName="Name"
-								description="Name of the model" required="true" readOnly="true" />
-							<c:simple-property name="sourceName"
-								displayName="Source Name" description="Source name for this model"
-								required="false" readOnly="true" />
-							<c:simple-property name="translatorName"
-								displayName="Translator Name" description="Name of the translator"
-								required="false" readOnly="true" />
-							<c:simple-property name="jndiName" displayName="Connection JNDI Name"
-								description="JNDI name for this connection" required="false" />
-							<c:simple-property name="visibility"
-								displayName="Visible" description="Visibility of the model"
-								required="true" type="boolean" readOnly="true">
-							</c:simple-property>
-							<c:simple-property name="supportsMultiSource"
-								displayName="Supports Multi-source?"
-								description="Determines if this model supports multi-source bindings"
-								required="true" default="true" type="boolean" readOnly="true" />
-						</c:map-property>
-					</c:list-property>
-
-					<c:list-property name="multiSourceModels"
-						description="The multi-source model sources for this VDB">
-						<c:map-property name="map" readOnly="false">
-							<c:simple-property name="name" displayName="Name"
-								description="Name of the model" required="true" readOnly="true" />
-							<c:simple-property name="sourceName"
-								displayName="Source Name" description="Source name for this model"
-								readOnly="true" />
-							<c:simple-property name="translatorName"
-								displayName="Translator Name" description="Name of the translator"
-								required="true" />
-							<c:simple-property name="jndiName" displayName="Connection JNDI Name"
-								description="JNDI name for this connection" required="false" />
-						</c:map-property>
-					</c:list-property>
-
-					<c:list-property name="logicalModels" readOnly="true"
-						description="The logical models for this VDB">
-						<c:map-property name="map">
-							<c:simple-property name="name" displayName="Name"
-								description="Name of the model" required="true" readOnly="true" />
-							<c:simple-property name="type" displayName="Type"
-								description="type of logical model" required="true" readOnly="true" />
-							<c:simple-property name="visibility"
-								displayName="Visible" description="Visbility of the model"
-								required="true" default="true" readOnly="true" />
-						</c:map-property>
-					</c:list-property>
-				</c:group>
-				<c:group name="errors" displayName="Errors" hiddenByDefault="false">
-					<c:list-property name="errorList" description="VDB Errors"
-						summary="true" readOnly="true">
-						<c:map-property name="errorMap" summary="true">
-							<c:simple-property name="severity" displayName="Severity"
-								description="Severity" readOnly="true" summary="true" />
-							<c:simple-property name="message" displayName="Message"
-								description="Error message" readOnly="true" summary="true" />
-						</c:map-property>
-					</c:list-property>
-				</c:group>
-			</resource-configuration>
-
-			<service name="Data Roles" description="Data Roles for this VDB"
-				class="DataRoleComponent" discovery="DataRoleDiscoveryComponent">
-
-				<resource-configuration>
-					<c:simple-property name="name" displayName="Name"
-						description="Name of the data role" readOnly="true" required="false" />
-					<c:simple-property name="anyAuthenticated"
-						displayName="Any Authenticated" type="boolean"
-						description="Indicates if the role is mapped to any authenticated user"
-						readOnly="false" required="false" />
-					<c:simple-property name="description"
-						displayName="Description" type="string" description="Description of this data role"
-						readOnly="true" required="false" />
-					<c:list-property name="mappedRoleNameList"
-						readOnly="false" required="false" displayName="Mapped Role Names"
-						description="Mapped role names for this data role">
-						<c:map-property name="map" readOnly="false">
-							<c:simple-property name="name" displayName="Name"
-								description="Name of this mapped role" readOnly="true" />
-						</c:map-property>
-					</c:list-property>
-				</resource-configuration>
-
-			</service>
-
-		</service>
-
-		<service name="Translators" description="Teiid Translators"
-			class="TranslatorComponent" discovery="TranslatorDiscoveryComponent"
-			createDeletePolicy="both" creationDataType="configuration">
-
-			<resource-configuration>
-				<c:simple-property name="name" displayName="Name"
-					description="Name of the translator" readOnly="true" required="false" />
-				<c:simple-property name="description" displayName="Description"
-					description="Description the translator" readOnly="true" required="false" />
-
-				<c:list-property name="translatorList" readOnly="true"
-					required="false" displayName="Properties" description="Translator properties">
-					<c:map-property name="properties" readOnly="true">
-						<c:simple-property name="name" displayName="Name"
-							description="Name of this property" readOnly="true" />
-						<c:simple-property name="value" displayName="Value"
-							description="Value of this property" readOnly="true" />
-					</c:map-property>
-				</c:list-property>
-
-			</resource-configuration>
-
-		</service>
-
-	</server>
-
-</plugin>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/console/src/main/resources/META-INF/rhq-plugin.xml (from rev 2707, branches/7.2.x/console/src/main/resources/META-INF/rhq-plugin.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/console/src/main/resources/META-INF/rhq-plugin.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/console/src/main/resources/META-INF/rhq-plugin.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,714 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+
+	<!--
+		* JBoss, Home of Professional Open Source. * See the COPYRIGHT.txt
+		file distributed with this work for information * regarding copyright
+		ownership. Some portions may be licensed * to Red Hat, Inc. under one
+		or more contributor license agreements. * * This library is free of
+		the GNU Lesser General Public * License as published by the Free
+		Software Foundation; either * version 2.1 of the License, or (at your
+		option) any later version. * * This library is distributed in the hope
+		that it will be useful, * but WITHOUT ANY WARRANTY; without even the
+		implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR
+		PURPOSE. See the GNU * Lesser General Public License for more details.
+		* * You should have received a copy of the GNU Lesser General Public *
+		License along with this library; if not, write to the Free Software *
+		Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
+		02110-1301 USA. */
+	-->
+	
+	<!DOCTYPE plugin [
+
+<!ENTITY managedObjectMetrics '
+    <metric property="runState" displayType="summary"
+            defaultOn="true" defaultInterval="30000" dataType="trait" category="performance"/>
+'>
+
+<!ENTITY translatorConfiguration '
+
+    <c:list-property name="translatorList" description="Properties for this translator"
+						readOnly="true">
+						<c:simple-property name="name" displayName="Name"
+							description="Name of the translator" />
+						<c:simple-property name="execution-factory-class" displayName="execution-factory-class"
+							description="Connector Class" />	
+						 <c:list-property name="translatorList" description="Properties for this translator" readOnly="true">
+						<c:map-property name="translator-properties" >
+							<c:simple-property name="name" displayName="Name"
+								description="Name of this property" readOnly="true" />
+							<c:simple-property name="value" displayName="Value"
+								description="Value of this property" />
+							<c:simple-property name="description" displayName="Description"
+								description="Description of this property" />
+						</c:map-property>						
+	</c:list-property>
+	
+'>			
+		
+<!ENTITY accessTranslatorConfiguration '
+	<resource-configuration>
+    <c:list-property name="translatorList" description="Properties for this translator"
+						readOnly="true">
+						<c:map-property name="translatorMap">
+							<c:simple-property name="name" displayName="Name"
+								description="Name of this property" readOnly="true" />
+							<c:simple-property name="value" displayName="Value"
+								description="Value of this property" readOnly="true" />
+							<c:simple-property name="description" displayName="Description"
+								description="Description of this property" readOnly="true" />
+						</c:map-property>
+	</c:list-property>
+	</resource-configuration>    
+    
+'>					
+
+
+]>
+
+	<!--
+		############################################# END OF XML ENTITIES
+		###############################################
+	-->
+
+
+
+<plugin name="TeiidPlugin" displayName="Teiid Plugin" package="org.teiid.rhq.plugin"
+	version="2.0.0" description="Supports management and monitoring of JBoss Teiid"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:xmlns:rhq-plugin"
+	xmlns:c="urn:xmlns:rhq-configuration">
+
+	<depends plugin="JBossAS5" useClasses="true" />
+
+	<server name="Data Services" description="Teiid Data Services"
+		class="PlatformComponent" discovery="PlatformDiscoveryComponent"
+		singleton="true">
+
+		<runs-inside>
+			<parent-resource-type name="JBossAS Server"
+				plugin="JBossAS5" />
+		</runs-inside>
+
+		<operation name="getLongRunningRequests" displayName="View current long running queries"
+			description="List current queries executing against the Teiid System that have surpassed the long running query threshhold">
+			<results>
+				<c:list-property name="list">
+					<c:map-property name="map">
+						<c:simple-property displayName="Session ID"
+							name="getSessionId" type="string"
+							description="The name of the resource whose availability is being reported" />
+						<c:simple-property displayName="Request ID"
+							name="getRequestId" type="string" description="The id for the request" />
+						<c:simple-property displayName="SQL String"
+							name="getCommand" type="string" description="The SQL string for this query" />
+						<c:simple-property displayName="Source Request"
+							name="sourceRequest" type="string"
+							description="If false,this is the top level query. If true, this a physical source query." />
+						<c:simple-property displayName="Execution ID"
+							name="getExecutionId" type="string"
+							description="The execution id for this request (if this is a physical source query)" />
+						<c:simple-property displayName="Start Time"
+							name="getCreatedTime" type="string" description="The time this query began" />
+						<c:simple-property displayName="Start Time"
+							name="getProcessingTime" type="string" description="Processing time for this request" />
+						<c:simple-property displayName="Transaction ID"
+							name="getTransactionId" type="string"
+							description="The transaction XID if there is a transaction involved" />
+						<c:simple-property displayName="Node ID" name="getNodeId"
+							type="string" description="The node ID of this query" />
+					</c:map-property>
+				</c:list-property>
+			</results>
+		</operation>
+
+		<operation name="getSessions" displayName="View current sessions"
+			description="Get current sessions connected to the Teiid instance">
+			<results>
+
+				<c:list-property name="list" displayName="Current Sessions"
+					description="Sessions currently connected to the Teiid system"
+					required="false">
+					<c:map-property name="map">
+						<c:simple-property displayName="Session ID"
+							name="getSessionId" type="string" description="The identifier for this session" />
+						<c:simple-property displayName="Application Name"
+							name="getApplicationName" type="string"
+							description="The application associated with Session" />
+						<c:simple-property displayName="Created Time"
+							name="getCreatedTime" type="string" description="When the session was created" />
+						<c:simple-property displayName="Client Host"
+							name="getClientHostName" type="string"
+							description="Host name from where the session created" />
+						<c:simple-property displayName="IP Address"
+							name="getIPAddress" type="string"
+							description="IP address from where this session was created" />
+						<c:simple-property displayName="Last ping time"
+							name="getLastPingTime" type="string" description="Last ping time" />
+						<c:simple-property displayName="User Name" name="getUserName"
+							type="string" description="User associated with this session" />
+						<c:simple-property displayName="VDB Name" name="getVDBName"
+							type="string" description="VDB associated with this session" />
+						<c:simple-property displayName="Security Domain"
+							name="getSecurityDomain" type="string"
+							description="Security Domain that session logged into" />
+					</c:map-property>
+				</c:list-property>
+			</results>
+		</operation>
+
+		<operation name="deployVdbByUrl" displayName="Deploy a VDB via URL"
+			description="Deploy a VDB using a URL">
+			<parameters>
+				<c:simple-property displayName="VDB URL" name="vdbUrl"
+					type="file" required="true" description="The URL of the VDB to deploy" />
+				<c:simple-property displayName="VDB Deploy File Name"
+					name="vdbDeployName" type="string" required="true"
+					description="The deployment file name to use. Must match the VDB Name you are deploying." />
+				<c:simple-property displayName="VDB Version" name="vdbVersion"
+					type="integer" required="false"
+					description="The version to use for the deployed VDB (leave blank for overwrite of version one)" />
+			</parameters>
+		</operation>
+
+
+		<operation name="terminateSession" displayName="Terminate Session"
+			description="Terminate a specified session">
+			<parameters>
+				<c:simple-property displayName="SessionID" name="sessionID"
+					type="long" required="true" description="The ID of the session to terminate" />
+			</parameters>
+		</operation>
+
+
+		<operation name="getRequests" displayName="View current requests"
+			description="Get current requests executing against this Teiid instance">
+			<results>
+
+				<c:list-property name="list" displayName="Current Request"
+					description="Requests currently executing against the Teiid system"
+					required="false">
+					<c:map-property name="map">
+						<c:simple-property displayName="Request ID"
+							name="getRequestId" type="string" description="The request identifier" />
+						<c:simple-property displayName="Session ID"
+							name="getSessionId" type="string" description="Session identifier" />
+						<c:simple-property displayName="Execution ID"
+							name="getExecutionId" type="string" description="Unique Identifier for Request" />
+						<c:simple-property displayName="Created Time"
+							name="getCreatedTime" type="string" description="Time when request submitted" />
+						<c:simple-property displayName="Processing Time"
+							name="getProcessingTime" type="string" description="Processing time for the request" />
+						<c:simple-property displayName="Last ping time"
+							name="getCommand" type="string" description="SQL Command" />
+						<c:simple-property displayName="Connector level request?"
+							name="sourceRequest" type="string"
+							description="True if this is a connector level request" />
+						<c:simple-property displayName="Node ID" name="getNodeId"
+							type="string" description="The node identifier" />
+						<c:simple-property displayName="Tansaction identifier"
+							name="getTransactionId" type="string"
+							description="Transaction XID if a transaction is involved" />
+					</c:map-property>
+				</c:list-property>
+			</results>
+		</operation>
+
+		<operation name="cancelRequest" displayName="Terminate request"
+			description="Terminate the processing of a query and its source queries">
+			<parameters>
+				<c:simple-property displayName="Session ID" name="sessionID"
+					type="long" required="true"
+					description="The ID of the session that the request to cancel is associated with" />
+				<c:simple-property displayName="Request ID" name="requestID"
+					type="long" required="true" description="The ID of the request to cancel" />
+			</parameters>
+		</operation>
+
+		<operation name="getTransactions" displayName="View current transactions"
+			description="Get current transactions executing against this VDB">
+			<results>
+				<c:list-property name="list" displayName="Current Transactions"
+					description="Transactions currently executing against the Teiid system"
+					required="false">
+					<c:map-property name="map">
+						<c:simple-property displayName="Transaction ID"
+							name="getId" type="string"
+							description="The Xid string for GLOBAL transactions or the Transaction id string LOCAL/REQUEST." />
+						<c:simple-property displayName="Session ID"
+							name="getAssociatedSession" type="string"
+							description="Get the session associated with the this transaction. May be null for an unassociated Global transaction." />
+						<c:simple-property displayName="Scope" name="getScope"
+							type="string"
+							description="Get the scope for the transaction.  Will be one of GLOBAL, LOCAL, or REQUEST" />
+						<c:simple-property displayName="Created Time"
+							name="getCreatedTime" type="string" description="The local creation time." />
+					</c:map-property>
+				</c:list-property>
+			</results>
+		</operation>
+
+		<operation name="terminateTransaction" displayName="Terminate Transaction"
+			description="Terminate a specified transaction">
+			<parameters>
+				<c:simple-property displayName="Transaction ID"
+					name="transactionID" type="long" required="true"
+					description="The ID of the transaction to terminate" />
+			</parameters>
+		</operation>
+
+		<metric displayName="Query Count" defaultOn="true" displayType="detail"
+			category="throughput" property="queryCount"
+			description="The number of queries currently active." />
+
+		<metric displayName="Long Running Queries" defaultOn="true"
+			displayType="detail" category="performance" property="longRunningQueries"
+			description="The number of queries that have been running longer than the limit set for queries." />
+
+		<metric displayName="Session Count" defaultOn="true"
+			displayType="detail" category="throughput" property="sessionCount"
+			description="The number of user connections currently active." />
+
+		<metric displayName="Used Buffer Space" defaultOn="true"
+			displayType="detail" category="throughput" property="userBufferSpace"
+			description="The currently used file buffer space in MB." />
+
+		<metric displayName="Prepared Plan Cache Hit Ratio %"
+			defaultOn="true" displayType="detail" category="performance"
+			property="PREPARED_PLAN_CACHE.hitRatio" description="Percentage of positive cache hits" />
+
+		<metric displayName="Prepared Plan Cache Size" defaultOn="true"
+			displayType="detail" category="performance" property="PREPARED_PLAN_CACHE.totalEntries"
+			description="Current number of entries in cache" />
+
+		<metric displayName="Prepared Plan Cache # of Requests"
+			defaultOn="true" displayType="detail" category="performance"
+			property="PREPARED_PLAN_CACHE.requestCount" description="Total number of requests made against cache" />
+
+		<metric displayName="ResultSet Cache Hit Ratio %" defaultOn="true"
+			displayType="detail" category="performance"
+			property="QUERY_SERVICE_RESULT_SET_CACHE.hitRatio" description="Percentage of positive cache hits" />
+
+		<metric displayName="ResultSet Cache Size" defaultOn="true"
+			displayType="detail" category="performance"
+			property="QUERY_SERVICE_RESULT_SET_CACHE.totalEntries" description="Current number of entries in cache" />
+
+		<metric displayName="ResultSet Cache  # of Requests" defaultOn="true"
+			displayType="detail" category="performance"
+			property="QUERY_SERVICE_RESULT_SET_CACHE.requestCount" description="Total number of requests made against cache" />
+
+		<resource-configuration>
+			<c:group name="RuntimeEngineDeployer" displayName="Runtime Engine Properties (restart required before modifications take effect)"
+				hiddenByDefault="false">
+				<c:simple-property name="RuntimeEngineDeployer.maxRowsFetchSize"
+					displayName="Max Rows Fetch Size"
+					description="The maximum number of result set cache entries. 0 indicates no limit. (default 1024)"
+					required="false" readOnly="false" />
+				<c:simple-property name="RuntimeEngineDeployer.maxThreads" displayName="Max Threads"
+					description="Process pool maximum thread count. (default 64)"
+					required="false" readOnly="false" />                    
+                <c:simple-property name="RuntimeEngineDeployer.maxActivePlans"
+                    displayName="Maximum Concurrent Active plans"
+                    description="Increase this value on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts.(default 20)"
+                    required="false" readOnly="false" />                    
+				<c:simple-property name="RuntimeEngineDeployer.timeSliceInMilli"
+					displayName="Time Slice In Milliseconds"
+					description="Query processor time slice, in milliseconds. (default 2000)"
+					required="false" readOnly="false" />
+				<c:simple-property name="RuntimeEngineDeployer.lobChunkSizeInKB"
+					displayName="Lob Chunk Size In KB"
+					description="The max lob chunk size in KB transferred to the client for xml, blobs, clobs (default 100KB)"
+					required="false" readOnly="false" />				
+				<c:simple-property name="RuntimeEngineDeployer.preparedPlanCacheMaxCount"
+					displayName="Prepared Plan Cache Max Count"
+					description="The maximum number of query plans that are cached. Note: this is a memory based cache. (default 250)"
+					required="false" readOnly="false" />
+				<c:simple-property name="RuntimeEngineDeployer.queryThresholdInSecs"
+					displayName="Long Running Query Threshold"
+					description="Length of time in seconds before a query is considered long running"
+					required="false" readOnly="false" />
+                <c:simple-property name="RuntimeEngineDeployer.useDataRoles"
+                    displayName="Data Roles Enabled"
+                    description="Turn on role checking of resources based on the roles defined in VDB (default true)"
+                    required="false" readOnly="false" />                    
+			</c:group>
+            
+            <c:group name="ResultSetCacheConfig" displayName="ResultSet Cache Properties" hiddenByDefault="false">
+                <!-- the below property on  RuntimeEngineDeployer -->
+                <c:simple-property name="RuntimeEngineDeployer.resultSetCacheEnabled"
+                    displayName="Enabled"
+                    description="Denotes whether or not result set caching is enabled. (default true)"
+                    required="false" readOnly="false" type="boolean" />                                                    
+                <c:simple-property name="ResultSetCacheConfig.maxEntries"
+                    displayName="Max Entries"
+                    description="The maximum number of result set cache entries. -1 indicates no limit. (default 1024)"
+                    required="false" readOnly="false" />
+                <c:simple-property name="ResultSetCacheConfig.maxAgeInSeconds"
+                    displayName="Max Entry Age"
+                    description="The maximum age of a result set cache entry in seconds. -1 indicates no max. (default 7200)"
+                    required="false" readOnly="false" />            
+            </c:group>
+            
+			<c:group name="BufferService" displayName="Buffer Service Properties"
+				hiddenByDefault="false">
+				<c:simple-property name="BufferService.maxBufferSpace"
+					displayName="Max Buffer Space"
+					description="Max file storage space, in MB, to be used for buffer files (default 50G)"
+					required="false" readOnly="false" />
+				<c:simple-property name="BufferService.processorBatchSize"
+					displayName="Processor Batch Size"
+					description="The max row count of a batch sent internally within the query processor. Should be &lt;= the connectorBatchSize. (default 512)"
+					required="false" readOnly="false" />
+				<c:simple-property name="BufferService.connectorBatchSize"
+					displayName="Connector Batch Size"
+					description="The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024)"
+					required="false" readOnly="false" />
+				<c:simple-property name="BufferService.maxProcessingBatchesColumns"
+					displayName="Max Processing Batches Columns"
+					description="The number of batch columns guarenteed to a processing operation.  Set this value lower if the workload typically processes larger numbers of concurrent queries with large intermediate results from operations such as sorting, grouping, etc. (default 128)"
+					required="false" readOnly="false" />
+				<c:simple-property name="BufferService.maxFileSize" displayName="Max File Size"
+					description="Max file size for buffer files (default 2GB)"
+					required="false" readOnly="false" />
+				<c:simple-property name="BufferService.maxReserveBatchColumns"
+					displayName="Max Reserve Batch Columns"
+					description="The number of batch columns to allow in memory (default 16384).  This value should be set lower or higher depending on the available memory to Teiid in the VM.  16384 is considered a good default for a dedicated 32-bit VM running Teiid with a 1 gig heap."
+					required="false" readOnly="false" />
+			</c:group>
+			<c:group name="JdbcSocketConfiguration"	displayName="Jdbc Socket Configuration Properties" hiddenByDefault="false">
+                <c:simple-property name="JdbcSocketConfiguration.enabled" displayName="Enable"
+                    description="Enable Socket based JDBC access" required="false" readOnly="false" />            
+                <c:simple-property name="JdbcSocketConfiguration.hostName" displayName="Host Name"
+                    description="Host Name" required="false" readOnly="false" />
+				<c:simple-property name="JdbcSocketConfiguration.portNumber" displayName="Port Number"
+					description="Port Number" required="false" readOnly="false" />
+				<c:simple-property name="JdbcSocketConfiguration.sslEnabled" displayName="SSL Enabled"
+					description="SSL enabled" required="false" readOnly="true" type="boolean"
+					default="true" />
+				<c:simple-property name="JdbcSocketConfiguration.maxSocketThreads"
+					displayName="Max Socket Threads" description="Max NIO threads"
+					required="false" readOnly="false" />
+				<c:simple-property name="JdbcSocketConfiguration.inputBufferSize"
+					displayName="Input Buffer Size"
+					description="SO_RCVBUF size, 0 indicates that system default should be used (default 0)"
+					required="false" readOnly="false" />
+				<c:simple-property name="JdbcSocketConfiguration.outputBufferSize"
+					displayName="Output Buffer Size"
+					description="SO_SNDBUF size, 0 indicates that system default should be used (default 0)"
+					required="false" readOnly="false" />
+			</c:group>
+			<c:group name="SessionService" displayName="Session Service Properties"
+				hiddenByDefault="false">
+				<c:simple-property name="SessionService.sessionExpirationTimeLimit"
+					displayName="Session Expiration Time Limit"
+					description="Max allowed time before the session is terminated by the system, 0 indicates unlimited (default 0)"
+					required="false" readOnly="false" />
+				<c:simple-property name="SessionService.sessionMaxLimit"
+					displayName="Session Max Limit"
+					description="Maximum number of sessions allowed by the system (default 5000)"
+					required="false" readOnly="false" />
+			</c:group>
+		</resource-configuration>
+
+		<service name="Virtual Database (VDB)s" description="Teiid Data Services Virtual Databases"
+			class="VDBComponent" discovery="VDBDiscoveryComponent"
+			createDeletePolicy="both" creationDataType="content">
+
+			<operation name="getSessions" displayName="View VDB Sessions"
+				description="Get current sessions currently connected to this VDB">
+				<results>
+
+					<c:list-property name="list" displayName="Current VDB Sessions"
+						description="Sessions currently connected to this VDB" required="false">
+						<c:map-property name="map">
+							<c:simple-property displayName="Session ID"
+								name="getSessionId" type="string" description="The identifier for this session" />
+							<c:simple-property displayName="Application Name"
+								name="getApplicationName" type="string"
+								description="The application associated with Session" />
+							<c:simple-property displayName="Created Time"
+								name="getCreatedTime" type="string" description="When the session was created" />
+							<c:simple-property displayName="Client Host"
+								name="getClientHostName" type="string"
+								description="Host name from where the session created" />
+							<c:simple-property displayName="IP Address"
+								name="getIPAddress" type="string"
+								description="IP address from where this session was created" />
+							<c:simple-property displayName="Last ping time"
+								name="getLastPingTime" type="string" description="Last ping time" />
+							<c:simple-property displayName="User Name"
+								name="getUserName" type="string" description="User associated with this session" />
+							<c:simple-property displayName="Security Domain"
+								name="getSecurityDomain" type="string"
+								description="Security Domain that session logged into" />
+						</c:map-property>
+					</c:list-property>
+				</results>
+			</operation>
+
+			<operation name="getRequestsUsingVDB" displayName="View VDB requests"
+				description="Get current requests executing against this VDB">
+				<results>
+
+					<c:list-property name="list" displayName="Current Request"
+						description="Requests currently executing against the Teiid system"
+						required="false">
+						<c:map-property name="map">
+							<c:simple-property displayName="Request ID"
+								name="getRequestId" type="string" description="The request identifier" />
+							<c:simple-property displayName="Session ID"
+								name="getSessionId" type="string" description="Session identifier" />
+							<c:simple-property displayName="Execution ID"
+								name="getExecutionId" type="string" description="Unique Identifier for Request" />
+							<c:simple-property displayName="Created Time"
+								name="getCreatedTime" type="string" description="Time when request submitted" />
+							<c:simple-property displayName="Processing Time"
+								name="getProcessingTime" type="string" description="Processing time for the request" />
+							<c:simple-property displayName="Last ping time"
+								name="getCommand" type="string" description="SQL Command" />
+							<c:simple-property displayName="Connector level request?"
+								name="sourceRequest" type="string"
+								description="True if this is a connector level request" />
+							<c:simple-property displayName="Node ID" name="getNodeId"
+								type="string" description="The node identifier" />
+							<c:simple-property displayName="Tansaction identifier"
+								name="getTransactionId" type="string"
+								description="Transaction XID if a transaction is involved" />
+						</c:map-property>
+					</c:list-property>
+				</results>
+			</operation>
+
+			<operation name="getMaterializedViews" displayName="List Materialized View Info"
+				description="List any Materialized Views for this VDB">
+
+				<results>
+
+					<c:list-property name="list" displayName="Materialized Views"
+						description="List information related to Materialized Views, if any, for this VDB"
+						required="false">
+						<c:map-property name="map">
+							<c:simple-property displayName="Schema Name"
+								name="schemaName" type="string" description="Name of the schema that is materialized" />
+							<c:simple-property displayName="Name" name="name"
+								type="string" description="Name of the materialized table" />
+							<c:simple-property displayName="Target Schema Name"
+								name="targetSchemaName" type="string" description="Name of the materialized schema" />
+							<c:simple-property displayName="Target Name"
+								name="targetName" type="string" description="Name of target table" />
+							<c:simple-property displayName="Valid"
+								name="valid" type="string" description="Indicates if data in table is valid for use" />
+							<c:simple-property displayName="Current State"
+								name="loadState" type="string" description="Processing time for the request" />
+							<c:simple-property displayName="Last Updated"
+								name="updated" type="integer" description="Last time of data refresh" />
+							<c:simple-property displayName="Cardinality"
+								name="cardinality" type="integer" description="Row count" />
+						</c:map-property>
+					</c:list-property>
+				</results>
+			</operation>
+
+			<operation name="reloadMaterializedView" displayName="Refresh a Materialized View"
+				description="Refresh a given any Materialized View for this VDB">
+				<parameters>
+					<c:simple-property displayName="Materialized View Schema"
+						name="schema" type="string" required="true"
+						description="The schema name of the Materialized View to refresh" />
+					<c:simple-property displayName="Materialized View Name"
+						name="table" type="string" required="true"
+						description="The name of the Materialized View to refresh" />
+					<c:simple-property displayName="Invalidate Current Materialized View Table"
+						name="invalidate" type="boolean" required="true" default="false"
+						description="If yes, will block all queries against the current Materialized View table until data is refreshed." />
+				</parameters>
+
+				<results>
+					<c:simple-property displayName="Result" name="operationResult"
+						type="string" description="Result of refresh" />
+				</results>
+			</operation>
+
+			<metric displayName="Status" defaultOn="true" dataType="trait"
+				displayType="summary" category="availability" property="status"
+				description="The status of this VDB" />
+
+			<metric displayName="Errors" defaultOn="true" dataType="trait"
+				displayType="summary" category="availability" property="errorCount"
+				description="Whether or not errors exist for this VDB" />
+
+			<content name="vdb" displayName="VDB Archive" category="deployable"
+				isCreationType="true">
+			</content>
+
+			<resource-configuration>
+				<c:group name="general" displayName="General"
+					hiddenByDefault="false">
+					<c:simple-property name="name" type="string"
+						description="The Virtual Database Name" required="false" readOnly="true" />
+					<c:simple-property name="version" type="string"
+						description="The Virtual Database Version" required="false"
+						readOnly="true" />
+					<c:simple-property name="description" type="string"
+						description="The Virtual Database Description" required="false"
+						readOnly="true" />
+					<c:simple-property name="status" type="string"
+						description="The Virtual Database Status" required="false"
+						summary="true" readOnly="true">
+						<c:property-options>
+							<c:option value="ACTIVE" name="UP" />
+							<c:option value="INACTIVE" name="DOWN" default="true" />
+						</c:property-options>
+					</c:simple-property>
+					<c:simple-property name="connectionType" type="string"
+						description="Allowable Connections: 1) NONE - disallow new connections 2) BY VERSION - allow connections only if the version is specified or if this is the earliest 'BY VERSION' vdb and there are no vdbs marked as 'ANY' 
+3) ANY - allow connections with or without a version specified. If multiple versions of same VDB are deployed, connect to one specified with ANY, or if there are multiple VDBs with ANY then connect to the latest version with ANY "
+						required="false">
+						<c:property-options>
+							<c:option value="NONE" name="NONE" />
+							<c:option value="BY_VERSION" name="BY VERSION" default="true" />
+							<c:option value="ANY" name="ANY" />
+						</c:property-options>
+					</c:simple-property>
+					<c:simple-property name="url" type="string"
+						description="The Virtual Database URL" required="false" readOnly="true" />
+				</c:group>
+				<c:group name="Translators" displayName="Translators"
+					hiddenByDefault="false">
+					<c:list-property name="translators" displayName="Overrides"
+						readOnly="true" description="The translator overrides for this VDB">
+						<c:map-property name="map"
+							description="Translator Overrides for this VDB">
+							<c:simple-property name="name" displayName="Name"
+								description="Name of this translator instance" required="false"
+								readOnly="true" />
+							<c:simple-property name="type" displayName="Translator type"
+								description="Translator type" required="false" readOnly="true" />
+							<c:simple-property name="propertyName"
+								displayName="Property Name" description="Property Name"
+								required="false" readOnly="true" />
+							<c:simple-property name="propertyValue"
+								displayName="Property Value" description="Property Value"
+								required="false" readOnly="true" />
+						</c:map-property>
+					</c:list-property>
+				</c:group>
+				<c:group name="Models" displayName="Models" hiddenByDefault="false">
+					<c:list-property name="singleSourceModels"
+						readOnly="true" description="The source models for this VDB">
+						<c:map-property name="map" description="Properties for this model">
+							<c:simple-property name="name" displayName="Name"
+								description="Name of the model" required="true" readOnly="true" />
+							<c:simple-property name="sourceName"
+								displayName="Source Name" description="Source name for this model"
+								required="false" readOnly="true" />
+							<c:simple-property name="translatorName"
+								displayName="Translator Name" description="Name of the translator"
+								required="false" readOnly="true" />
+							<c:simple-property name="jndiName" displayName="Connection JNDI Name"
+								description="JNDI name for this connection" required="false" />
+							<c:simple-property name="visibility"
+								displayName="Visible" description="Visibility of the model"
+								required="true" type="boolean" readOnly="true">
+							</c:simple-property>
+							<c:simple-property name="supportsMultiSource"
+								displayName="Supports Multi-source?"
+								description="Determines if this model supports multi-source bindings"
+								required="true" default="true" type="boolean" readOnly="true" />
+						</c:map-property>
+					</c:list-property>
+
+					<c:list-property name="multiSourceModels"
+						description="The multi-source model sources for this VDB">
+						<c:map-property name="map" readOnly="false">
+							<c:simple-property name="name" displayName="Name"
+								description="Name of the model" required="true" readOnly="true" />
+							<c:simple-property name="sourceName"
+								displayName="Source Name" description="Source name for this model"
+								readOnly="true" />
+							<c:simple-property name="translatorName"
+								displayName="Translator Name" description="Name of the translator"
+								required="true" />
+							<c:simple-property name="jndiName" displayName="Connection JNDI Name"
+								description="JNDI name for this connection" required="false" />
+						</c:map-property>
+					</c:list-property>
+
+					<c:list-property name="logicalModels" readOnly="true"
+						description="The logical models for this VDB">
+						<c:map-property name="map">
+							<c:simple-property name="name" displayName="Name"
+								description="Name of the model" required="true" readOnly="true" />
+							<c:simple-property name="type" displayName="Type"
+								description="type of logical model" required="true" readOnly="true" />
+							<c:simple-property name="visibility"
+								displayName="Visible" description="Visbility of the model"
+								required="true" default="true" readOnly="true" />
+						</c:map-property>
+					</c:list-property>
+				</c:group>
+				<c:group name="errors" displayName="Errors" hiddenByDefault="false">
+					<c:list-property name="errorList" description="VDB Errors"
+						summary="true" readOnly="true">
+						<c:map-property name="errorMap" summary="true">
+							<c:simple-property name="severity" displayName="Severity"
+								description="Severity" readOnly="true" summary="true" />
+							<c:simple-property name="message" displayName="Message"
+								description="Error message" readOnly="true" summary="true" />
+						</c:map-property>
+					</c:list-property>
+				</c:group>
+			</resource-configuration>
+
+			<service name="Data Roles" description="Data Roles for this VDB"
+				class="DataRoleComponent" discovery="DataRoleDiscoveryComponent">
+
+				<resource-configuration>
+					<c:simple-property name="name" displayName="Name"
+						description="Name of the data role" readOnly="true" required="false" />
+					<c:simple-property name="anyAuthenticated"
+						displayName="Any Authenticated" type="boolean"
+						description="Indicates if the role is mapped to any authenticated user"
+						readOnly="false" required="false" />
+					<c:simple-property name="description"
+						displayName="Description" type="string" description="Description of this data role"
+						readOnly="true" required="false" />
+					<c:list-property name="mappedRoleNameList"
+						readOnly="false" required="false" displayName="Mapped Role Names"
+						description="Mapped role names for this data role">
+						<c:map-property name="map" readOnly="false">
+							<c:simple-property name="name" displayName="Name"
+								description="Name of this mapped role" readOnly="true" />
+						</c:map-property>
+					</c:list-property>
+				</resource-configuration>
+
+			</service>
+
+		</service>
+
+		<service name="Translators" description="Teiid Translators"
+			class="TranslatorComponent" discovery="TranslatorDiscoveryComponent"
+			createDeletePolicy="both" creationDataType="configuration">
+
+			<resource-configuration>
+				<c:simple-property name="name" displayName="Name"
+					description="Name of the translator" readOnly="true" required="false" />
+				<c:simple-property name="description" displayName="Description"
+					description="Description the translator" readOnly="true" required="false" />
+
+				<c:list-property name="translatorList" readOnly="true"
+					required="false" displayName="Properties" description="Translator properties">
+					<c:map-property name="properties" readOnly="true">
+						<c:simple-property name="name" displayName="Name"
+							description="Name of this property" readOnly="true" />
+						<c:simple-property name="value" displayName="Value"
+							description="Value of this property" readOnly="true" />
+					</c:map-property>
+				</c:list-property>
+
+			</resource-configuration>
+
+		</service>
+
+	</server>
+
+</plugin>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/documentation/admin-guide/pom.xml
===================================================================
--- branches/7.2.x/documentation/admin-guide/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/documentation/admin-guide/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
-  <parent>
-    <groupId>org.jboss.teiid</groupId>
-    <artifactId>documentation</artifactId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>admin-guide</artifactId>
-  <groupId>org.jboss.teiid.documentation</groupId>
-  <packaging>jdocbook</packaging>
-  <name>Admin Guide</name>
-  <description>The Teiid Admin manual</description>
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.jboss.maven.plugins</groupId>
-        <artifactId>maven-jdocbook-plugin</artifactId>
-        <version>2.1.2</version>
-        <extensions>true</extensions>
-        <dependencies>
-          <dependency>
-            <groupId>net.sf.docbook</groupId>
-            <artifactId>docbook</artifactId>
-            <version>1.74.0</version>
-          </dependency>        
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-docbook-xslt</artifactId>
-            <version>1.1.0</version>
-          </dependency>
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-jdocbook-style</artifactId>
-            <version>1.1.0</version>
-            <type>jdocbook-style</type>
-          </dependency>
-        </dependencies>
-        <configuration>
-          <sourceDocumentName>admin_guide.xml</sourceDocumentName>
-          <imageResource>
-            <directory>${basedir}/src/main/docbook/en-US</directory>
-            <excludes>
-              <exclude>*.xml</exclude>
-              <exclude>**/*.xml</exclude>
-              <exclude>*.zargo</exclude>
-              <exclude>**/*.zargo</exclude>
-            </excludes>
-          </imageResource>
-          <formats>
-            <format>
-              <formatName>pdf</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
-              <finalName>teiid_admin_guide.pdf</finalName>
-            </format>
-            <format>
-              <formatName>html_single</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-            <format>
-              <formatName>html</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-          </formats>
-          <options>
-            <xincludeSupported>true</xincludeSupported>
-            <xmlTransformerType>saxon</xmlTransformerType>  
-            <docbookVersion>1.72.0</docbookVersion>             
-            <localeSeparator>-</localeSeparator>
-            <useRelativeImageUris>false</useRelativeImageUris>
-          </options>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-</project>

Copied: tags/teiid-parent-7.2.0.Final/documentation/admin-guide/pom.xml (from rev 2708, branches/7.2.x/documentation/admin-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/documentation/admin-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/documentation/admin-guide/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+  <parent>
+    <groupId>org.jboss.teiid</groupId>
+    <artifactId>documentation</artifactId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>admin-guide</artifactId>
+  <groupId>org.jboss.teiid.documentation</groupId>
+  <packaging>jdocbook</packaging>
+  <name>Admin Guide</name>
+  <description>The Teiid Admin manual</description>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.jboss.maven.plugins</groupId>
+        <artifactId>maven-jdocbook-plugin</artifactId>
+        <version>2.1.2</version>
+        <extensions>true</extensions>
+        <dependencies>
+          <dependency>
+            <groupId>net.sf.docbook</groupId>
+            <artifactId>docbook</artifactId>
+            <version>1.74.0</version>
+          </dependency>        
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-docbook-xslt</artifactId>
+            <version>1.1.0</version>
+          </dependency>
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-jdocbook-style</artifactId>
+            <version>1.1.0</version>
+            <type>jdocbook-style</type>
+          </dependency>
+        </dependencies>
+        <configuration>
+          <sourceDocumentName>admin_guide.xml</sourceDocumentName>
+          <imageResource>
+            <directory>${basedir}/src/main/docbook/en-US</directory>
+            <excludes>
+              <exclude>*.xml</exclude>
+              <exclude>**/*.xml</exclude>
+              <exclude>*.zargo</exclude>
+              <exclude>**/*.zargo</exclude>
+            </excludes>
+          </imageResource>
+          <formats>
+            <format>
+              <formatName>pdf</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+              <finalName>teiid_admin_guide.pdf</finalName>
+            </format>
+            <format>
+              <formatName>html_single</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+            <format>
+              <formatName>html</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+          </formats>
+          <options>
+            <xincludeSupported>true</xincludeSupported>
+            <xmlTransformerType>saxon</xmlTransformerType>  
+            <docbookVersion>1.72.0</docbookVersion>             
+            <localeSeparator>-</localeSeparator>
+            <useRelativeImageUris>false</useRelativeImageUris>
+          </options>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/documentation/admin-guide/src/main/docbook/en-US/content/appendix-a.xml
===================================================================
--- branches/7.2.x/documentation/admin-guide/src/main/docbook/en-US/content/appendix-a.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/documentation/admin-guide/src/main/docbook/en-US/content/appendix-a.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,60 +0,0 @@
-<appendix id="faq">
-  <title>AdminShell Frequently Asked Questions</title>
-  <qandaset>
-  
-    <qandaentry>
-      <question>
-        <para>Why won't the adminhelp command work in the Console tool?</para>
-      </question>
-      <answer>
-        <para>The Console environment does not understand Shell commands (load, help, adminhelp, etc.), since they are not directly supported by Groovy.  In the Console you should use the equivalent functional form / Groovy, e.g. instead of adminhelp, adminHelp()</para>
-      </answer>
-    </qandaentry>
-  
-    <qandaentry>
-      <question>
-        <para>Are there any pre-built scripts available?</para>
-      </question>
-      <answer>
-        <para>Currently no, but we will provide samples in subsequent releases.</para>
-      </answer>
-    </qandaentry>
-    
-    <qandaentry>
-      <question>
-        <para>I have written a very useful script to do XYZ, I would like this to be part of the distribution?</para>
-      </question>
-      <answer>
-        <para>Yes, we would love to hear from users. Please submit the script through the <ulink url="https://jira.jboss.org/jira/browse/TEIID">Teiid JIRA</ulink>, and if this script popular, we will include the script in the scripts library in the following releases.</para>
-      </answer>
-    </qandaentry>
-
-    <qandaentry>
-      <question>
-        <para>What is different between "connectAsAdmin()" and "connect()"?</para>
-      </question>
-      <answer>
-        <para>The connectAsAdmin methods create a contextual connection to the AdminAPI of the Teiid Server.  The connect methods return an extension of the Groovy Sql object to be used for Sql calls to the Teiid Server.</para>
-      </answer>
-    </qandaentry>
-
-    <qandaentry>
-      <question>
-        <para>Is IDE support available for writing the scripts?</para>
-      </question>
-      <answer>
-        <para>The Admin Console tool is a light-weight IDE.  Full IDE support is available for Groovy, but requires manual manipulation of the class path and script imports.  See <link linkend="other_environments">using AdminShell methods in other environments</link>.</para>
-      </answer>
-    </qandaentry>
-
-    <qandaentry>
-      <question>
-        <para>Is debugging support available?</para>
-      </question>
-      <answer>
-        <para>The interactive shell and console do have built-in support for inspection of the current state.  Performing line based debugging is beyond the scope of this document.</para>
-      </answer>
-    </qandaentry>
-        
-  </qandaset>
-</appendix>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/documentation/admin-guide/src/main/docbook/en-US/content/appendix-a.xml (from rev 2707, branches/7.2.x/documentation/admin-guide/src/main/docbook/en-US/content/appendix-a.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/documentation/admin-guide/src/main/docbook/en-US/content/appendix-a.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/documentation/admin-guide/src/main/docbook/en-US/content/appendix-a.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,71 @@
+<appendix id="faq">
+  <title>AdminShell Frequently Asked Questions</title>
+  <qandaset>
+  
+    <qandaentry>
+      <question>
+        <para>Why won't the adminhelp command work in the Console tool?</para>
+      </question>
+      <answer>
+        <para>The Console environment does not understand Shell commands (load, help, adminhelp, etc.), since they are not directly supported by Groovy.  In the Console you should use the equivalent functional form / Groovy, e.g. instead of adminhelp, adminHelp()</para>
+      </answer>
+    </qandaentry>
+  
+    <qandaentry>
+      <question>
+        <para>Are there any pre-built scripts available?</para>
+      </question>
+      <answer>
+        <para>Currently no, but we will provide samples in subsequent releases.</para>
+      </answer>
+    </qandaentry>
+    
+    <qandaentry>
+      <question>
+        <para>I have written a very useful script to do XYZ, I would like this to be part of the distribution?</para>
+      </question>
+      <answer>
+        <para>Yes, we would love to hear from users. Please submit the script through the <ulink url="https://jira.jboss.org/jira/browse/TEIID">Teiid JIRA</ulink>, and if this script popular, we will include the script in the scripts library in the following releases.</para>
+      </answer>
+    </qandaentry>
+
+    <qandaentry>
+      <question>
+        <para>What is different between "connectAsAdmin()" and "connect()"?</para>
+      </question>
+      <answer>
+        <para>The connectAsAdmin methods create a contextual connection to the AdminAPI of the Teiid Server.  The connect methods return an extension of the Groovy Sql object to be used for Sql calls to the Teiid Server.</para>
+      </answer>
+    </qandaentry>
+    
+    <qandaentry>
+      <question>
+        <para>What does "getAdmin()" call do? Why do I need it?</para>
+      </question>
+      <answer>
+        <para>"getAdmin()" returns this contextual connection object created when you executed "connectAsAdmin()" method.
+        This object implements the interface "org.teiid.adminapi.Admin" and AdminShell commands provided are 
+        wrappers around this API. Advanced users can use this API directly if the provided wrapper commands do not meet their needs.</para>
+      </answer>
+    </qandaentry>    
+
+    <qandaentry>
+      <question>
+        <para>Is IDE support available for writing the scripts?</para>
+      </question>
+      <answer>
+        <para>The Admin Console tool is a light-weight IDE.  Full IDE support is available for Groovy, but requires manual manipulation of the class path and script imports.  See <link linkend="other_environments">using AdminShell methods in other environments</link>.</para>
+      </answer>
+    </qandaentry>
+
+    <qandaentry>
+      <question>
+        <para>Is debugging support available?</para>
+      </question>
+      <answer>
+        <para>The interactive shell and console do have built-in support for inspection of the current state.  Performing line based debugging is beyond the scope of this document.</para>
+      </answer>
+    </qandaentry>
+        
+  </qandaset>
+</appendix>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/documentation/caching-guide/pom.xml
===================================================================
--- branches/7.2.x/documentation/caching-guide/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/documentation/caching-guide/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
-  <parent>
-    <groupId>org.jboss.teiid</groupId>
-    <artifactId>documentation</artifactId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>caching-guide</artifactId>
-  <groupId>org.jboss.teiid.documentation</groupId>
-  <packaging>jdocbook</packaging>
-  <name>Teiid Caching Guide</name>
-  <description>The Teiid Caching Guide</description>
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.jboss.maven.plugins</groupId>
-        <artifactId>maven-jdocbook-plugin</artifactId>
-        <version>2.1.2</version>
-        <extensions>true</extensions>
-        <dependencies>
-          <dependency>
-            <groupId>net.sf.docbook</groupId>
-            <artifactId>docbook</artifactId>
-            <version>1.74.0</version>
-          </dependency>           
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-docbook-xslt</artifactId>
-            <version>1.1.0</version>
-          </dependency>
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-jdocbook-style</artifactId>
-            <version>1.1.0</version>
-            <type>jdocbook-style</type>
-          </dependency>
-        </dependencies>
-        <configuration>
-          <sourceDocumentName>main.xml</sourceDocumentName>
-          <imageResource>
-            <directory>${basedir}/src/main/docbook/en-US</directory>
-            <excludes>
-              <exclude>*.xml</exclude>
-              <exclude>**/*.xml</exclude>
-              <exclude>*.zargo</exclude>
-              <exclude>**/*.zargo</exclude>
-            </excludes>
-          </imageResource>
-          <formats>
-            <format>
-              <formatName>pdf</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
-              <finalName>teiid_caching_guide.pdf</finalName>
-            </format>
-            <format>
-              <formatName>html_single</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-            <format>
-              <formatName>html</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-          </formats>
-          <options>
-            <xincludeSupported>true</xincludeSupported>
-            <xmlTransformerType>saxon</xmlTransformerType>  
-            <docbookVersion>1.72.0</docbookVersion>            
-            <localeSeparator>-</localeSeparator>
-            <useRelativeImageUris>false</useRelativeImageUris>
-          </options>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/documentation/caching-guide/pom.xml (from rev 2708, branches/7.2.x/documentation/caching-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/documentation/caching-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/documentation/caching-guide/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+  <parent>
+    <groupId>org.jboss.teiid</groupId>
+    <artifactId>documentation</artifactId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>caching-guide</artifactId>
+  <groupId>org.jboss.teiid.documentation</groupId>
+  <packaging>jdocbook</packaging>
+  <name>Teiid Caching Guide</name>
+  <description>The Teiid Caching Guide</description>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.jboss.maven.plugins</groupId>
+        <artifactId>maven-jdocbook-plugin</artifactId>
+        <version>2.1.2</version>
+        <extensions>true</extensions>
+        <dependencies>
+          <dependency>
+            <groupId>net.sf.docbook</groupId>
+            <artifactId>docbook</artifactId>
+            <version>1.74.0</version>
+          </dependency>           
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-docbook-xslt</artifactId>
+            <version>1.1.0</version>
+          </dependency>
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-jdocbook-style</artifactId>
+            <version>1.1.0</version>
+            <type>jdocbook-style</type>
+          </dependency>
+        </dependencies>
+        <configuration>
+          <sourceDocumentName>main.xml</sourceDocumentName>
+          <imageResource>
+            <directory>${basedir}/src/main/docbook/en-US</directory>
+            <excludes>
+              <exclude>*.xml</exclude>
+              <exclude>**/*.xml</exclude>
+              <exclude>*.zargo</exclude>
+              <exclude>**/*.zargo</exclude>
+            </excludes>
+          </imageResource>
+          <formats>
+            <format>
+              <formatName>pdf</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+              <finalName>teiid_caching_guide.pdf</finalName>
+            </format>
+            <format>
+              <formatName>html_single</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+            <format>
+              <formatName>html</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+          </formats>
+          <options>
+            <xincludeSupported>true</xincludeSupported>
+            <xmlTransformerType>saxon</xmlTransformerType>  
+            <docbookVersion>1.72.0</docbookVersion>            
+            <localeSeparator>-</localeSeparator>
+            <useRelativeImageUris>false</useRelativeImageUris>
+          </options>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/documentation/client-developers-guide/pom.xml
===================================================================
--- branches/7.2.x/documentation/client-developers-guide/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/documentation/client-developers-guide/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
-  <parent>
-    <groupId>org.jboss.teiid</groupId>
-    <artifactId>documentation</artifactId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>client-developers-guide</artifactId>
-  <groupId>org.jboss.teiid.documentation</groupId>
-  <packaging>jdocbook</packaging>
-  <name>Teiid Client Developers Guide</name>
-  <description>The Client Developers Guide</description>
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.jboss.maven.plugins</groupId>
-        <artifactId>maven-jdocbook-plugin</artifactId>
-        <version>2.1.2</version>
-        <extensions>true</extensions>
-        <dependencies>
-          <dependency>
-            <groupId>net.sf.docbook</groupId>
-            <artifactId>docbook</artifactId>
-            <version>1.74.0</version>
-          </dependency>           
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-docbook-xslt</artifactId>
-            <version>1.1.0</version>
-          </dependency>
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-jdocbook-style</artifactId>
-            <version>1.1.0</version>
-            <type>jdocbook-style</type>
-          </dependency>
-        </dependencies>
-        <configuration>
-          <sourceDocumentName>main.xml</sourceDocumentName>
-          <imageResource>
-            <directory>${basedir}/src/main/docbook/en-US</directory>
-            <excludes>
-              <exclude>*.xml</exclude>
-              <exclude>**/*.xml</exclude>
-              <exclude>*.zargo</exclude>
-              <exclude>**/*.zargo</exclude>
-            </excludes>
-          </imageResource>
-          <formats>
-            <format>
-              <formatName>pdf</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
-              <finalName>teiid_client_developers_guide.pdf</finalName>
-            </format>
-            <format>
-              <formatName>html_single</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-            <format>
-              <formatName>html</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-          </formats>
-          <options>
-            <xincludeSupported>true</xincludeSupported>
-            <xmlTransformerType>saxon</xmlTransformerType>  
-            <docbookVersion>1.72.0</docbookVersion>            
-            <localeSeparator>-</localeSeparator>
-            <useRelativeImageUris>false</useRelativeImageUris>
-          </options>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/documentation/client-developers-guide/pom.xml (from rev 2708, branches/7.2.x/documentation/client-developers-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/documentation/client-developers-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/documentation/client-developers-guide/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+  <parent>
+    <groupId>org.jboss.teiid</groupId>
+    <artifactId>documentation</artifactId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>client-developers-guide</artifactId>
+  <groupId>org.jboss.teiid.documentation</groupId>
+  <packaging>jdocbook</packaging>
+  <name>Teiid Client Developers Guide</name>
+  <description>The Client Developers Guide</description>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.jboss.maven.plugins</groupId>
+        <artifactId>maven-jdocbook-plugin</artifactId>
+        <version>2.1.2</version>
+        <extensions>true</extensions>
+        <dependencies>
+          <dependency>
+            <groupId>net.sf.docbook</groupId>
+            <artifactId>docbook</artifactId>
+            <version>1.74.0</version>
+          </dependency>           
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-docbook-xslt</artifactId>
+            <version>1.1.0</version>
+          </dependency>
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-jdocbook-style</artifactId>
+            <version>1.1.0</version>
+            <type>jdocbook-style</type>
+          </dependency>
+        </dependencies>
+        <configuration>
+          <sourceDocumentName>main.xml</sourceDocumentName>
+          <imageResource>
+            <directory>${basedir}/src/main/docbook/en-US</directory>
+            <excludes>
+              <exclude>*.xml</exclude>
+              <exclude>**/*.xml</exclude>
+              <exclude>*.zargo</exclude>
+              <exclude>**/*.zargo</exclude>
+            </excludes>
+          </imageResource>
+          <formats>
+            <format>
+              <formatName>pdf</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+              <finalName>teiid_client_developers_guide.pdf</finalName>
+            </format>
+            <format>
+              <formatName>html_single</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+            <format>
+              <formatName>html</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+          </formats>
+          <options>
+            <xincludeSupported>true</xincludeSupported>
+            <xmlTransformerType>saxon</xmlTransformerType>  
+            <docbookVersion>1.72.0</docbookVersion>            
+            <localeSeparator>-</localeSeparator>
+            <useRelativeImageUris>false</useRelativeImageUris>
+          </options>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/documentation/developer-guide/pom.xml
===================================================================
--- branches/7.2.x/documentation/developer-guide/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/documentation/developer-guide/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
-  <parent>
-    <groupId>org.jboss.teiid</groupId>
-    <artifactId>documentation</artifactId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>developer-guide</artifactId>
-  <groupId>org.jboss.teiid.documentation</groupId>
-  <packaging>jdocbook</packaging>
-  <name>Developer's Guide</name>
-  <description>The Teiid Developer's Guide</description>
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.jboss.maven.plugins</groupId>
-        <artifactId>maven-jdocbook-plugin</artifactId>
-        <version>2.1.2</version>
-        <extensions>true</extensions>
-        <dependencies>
-          <dependency>
-            <groupId>net.sf.docbook</groupId>
-            <artifactId>docbook</artifactId>
-            <version>1.74.0</version>
-          </dependency>          
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-docbook-xslt</artifactId>
-            <version>1.1.0</version>
-          </dependency>
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-jdocbook-style</artifactId>
-            <version>1.1.0</version>
-            <type>jdocbook-style</type>
-          </dependency>
-        </dependencies>
-        <configuration>
-          <sourceDocumentName>Developer_Guide.xml</sourceDocumentName>
-          <imageResource>
-            <directory>${basedir}/src/main/docbook/en-US</directory>
-            <excludes>
-              <exclude>*.xml</exclude>
-              <exclude>**/*.xml</exclude>
-              <exclude>*.zargo</exclude>
-              <exclude>**/*.zargo</exclude>
-            </excludes>
-          </imageResource>
-          <formats>
-            <format>
-              <formatName>pdf</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
-              <finalName>teiid_developer_guide.pdf</finalName>
-            </format>
-            <format>
-              <formatName>html_single</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-            <format>
-              <formatName>html</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-          </formats>
-          <options>
-            <xincludeSupported>true</xincludeSupported>
-            <xmlTransformerType>saxon</xmlTransformerType>  
-            <docbookVersion>1.72.0</docbookVersion>              
-            <localeSeparator>-</localeSeparator>
-            <useRelativeImageUris>false</useRelativeImageUris>
-          </options>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-</project>

Copied: tags/teiid-parent-7.2.0.Final/documentation/developer-guide/pom.xml (from rev 2708, branches/7.2.x/documentation/developer-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/documentation/developer-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/documentation/developer-guide/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+  <parent>
+    <groupId>org.jboss.teiid</groupId>
+    <artifactId>documentation</artifactId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>developer-guide</artifactId>
+  <groupId>org.jboss.teiid.documentation</groupId>
+  <packaging>jdocbook</packaging>
+  <name>Developer's Guide</name>
+  <description>The Teiid Developer's Guide</description>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.jboss.maven.plugins</groupId>
+        <artifactId>maven-jdocbook-plugin</artifactId>
+        <version>2.1.2</version>
+        <extensions>true</extensions>
+        <dependencies>
+          <dependency>
+            <groupId>net.sf.docbook</groupId>
+            <artifactId>docbook</artifactId>
+            <version>1.74.0</version>
+          </dependency>          
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-docbook-xslt</artifactId>
+            <version>1.1.0</version>
+          </dependency>
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-jdocbook-style</artifactId>
+            <version>1.1.0</version>
+            <type>jdocbook-style</type>
+          </dependency>
+        </dependencies>
+        <configuration>
+          <sourceDocumentName>Developer_Guide.xml</sourceDocumentName>
+          <imageResource>
+            <directory>${basedir}/src/main/docbook/en-US</directory>
+            <excludes>
+              <exclude>*.xml</exclude>
+              <exclude>**/*.xml</exclude>
+              <exclude>*.zargo</exclude>
+              <exclude>**/*.zargo</exclude>
+            </excludes>
+          </imageResource>
+          <formats>
+            <format>
+              <formatName>pdf</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+              <finalName>teiid_developer_guide.pdf</finalName>
+            </format>
+            <format>
+              <formatName>html_single</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+            <format>
+              <formatName>html</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+          </formats>
+          <options>
+            <xincludeSupported>true</xincludeSupported>
+            <xmlTransformerType>saxon</xmlTransformerType>  
+            <docbookVersion>1.72.0</docbookVersion>              
+            <localeSeparator>-</localeSeparator>
+            <useRelativeImageUris>false</useRelativeImageUris>
+          </options>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/documentation/pom.xml
===================================================================
--- branches/7.2.x/documentation/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/documentation/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,21 +0,0 @@
-<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">
-  <parent>
-    <artifactId>teiid-parent</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <groupId>org.jboss.teiid</groupId>
-  <artifactId>documentation</artifactId>
-  <packaging>pom</packaging>
-  <name>Documents</name>
-  <description>Teiid Documentation Aggregator</description>
-  <modules>
-    <module>admin-guide</module>
-    <module>reference</module>
-    <module>developer-guide</module>
-    <module>quick-start-example</module>
-    <module>client-developers-guide</module>
-    <module>caching-guide</module>
-  </modules>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/documentation/pom.xml (from rev 2708, branches/7.2.x/documentation/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/documentation/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/documentation/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,21 @@
+<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">
+  <parent>
+    <artifactId>teiid-parent</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.jboss.teiid</groupId>
+  <artifactId>documentation</artifactId>
+  <packaging>pom</packaging>
+  <name>Documents</name>
+  <description>Teiid Documentation Aggregator</description>
+  <modules>
+    <module>admin-guide</module>
+    <module>reference</module>
+    <module>developer-guide</module>
+    <module>quick-start-example</module>
+    <module>client-developers-guide</module>
+    <module>caching-guide</module>
+  </modules>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/documentation/quick-start-example/pom.xml
===================================================================
--- branches/7.2.x/documentation/quick-start-example/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/documentation/quick-start-example/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
-  <parent>
-    <groupId>org.jboss.teiid</groupId>
-    <artifactId>documentation</artifactId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>quick-start-example</artifactId>
-  <groupId>org.jboss.teiid.documentation</groupId>
-  <packaging>jdocbook</packaging>
-  <name>Quick Start Guide</name>
-  <description>The Teiid Quick Start guide</description>
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.jboss.maven.plugins</groupId>
-        <artifactId>maven-jdocbook-plugin</artifactId>
-        <version>2.1.2</version>
-        <extensions>true</extensions>
-        <dependencies>
-          <dependency>
-            <groupId>net.sf.docbook</groupId>
-            <artifactId>docbook</artifactId>
-            <version>1.74.0</version>
-          </dependency>             
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-docbook-xslt</artifactId>
-            <version>1.1.0</version>
-          </dependency>
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-jdocbook-style</artifactId>
-            <version>1.1.0</version>
-            <type>jdocbook-style</type>
-          </dependency>
-        </dependencies>
-        <configuration>
-          <sourceDocumentName>quick_start_example.xml</sourceDocumentName>
-          <imageResource>
-            <directory>${basedir}/src/main/docbook/en-US</directory>
-            <excludes>
-              <exclude>*.xml</exclude>
-              <exclude>**/*.xml</exclude>
-              <exclude>*.zargo</exclude>
-              <exclude>**/*.zargo</exclude>
-            </excludes>
-          </imageResource>
-          <formats>
-            <format>
-              <formatName>pdf</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
-              <finalName>teiid_quick_start_example.pdf</finalName>
-            </format>
-            <format>
-              <formatName>html_single</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-            <format>
-              <formatName>html</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-          </formats>
-          <options>
-            <xincludeSupported>true</xincludeSupported>
-            <xmlTransformerType>saxon</xmlTransformerType>  
-            <docbookVersion>1.72.0</docbookVersion>              
-            <localeSeparator>-</localeSeparator>
-            <useRelativeImageUris>false</useRelativeImageUris>
-          </options>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-</project>

Copied: tags/teiid-parent-7.2.0.Final/documentation/quick-start-example/pom.xml (from rev 2708, branches/7.2.x/documentation/quick-start-example/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/documentation/quick-start-example/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/documentation/quick-start-example/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+  <parent>
+    <groupId>org.jboss.teiid</groupId>
+    <artifactId>documentation</artifactId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>quick-start-example</artifactId>
+  <groupId>org.jboss.teiid.documentation</groupId>
+  <packaging>jdocbook</packaging>
+  <name>Quick Start Guide</name>
+  <description>The Teiid Quick Start guide</description>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.jboss.maven.plugins</groupId>
+        <artifactId>maven-jdocbook-plugin</artifactId>
+        <version>2.1.2</version>
+        <extensions>true</extensions>
+        <dependencies>
+          <dependency>
+            <groupId>net.sf.docbook</groupId>
+            <artifactId>docbook</artifactId>
+            <version>1.74.0</version>
+          </dependency>             
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-docbook-xslt</artifactId>
+            <version>1.1.0</version>
+          </dependency>
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-jdocbook-style</artifactId>
+            <version>1.1.0</version>
+            <type>jdocbook-style</type>
+          </dependency>
+        </dependencies>
+        <configuration>
+          <sourceDocumentName>quick_start_example.xml</sourceDocumentName>
+          <imageResource>
+            <directory>${basedir}/src/main/docbook/en-US</directory>
+            <excludes>
+              <exclude>*.xml</exclude>
+              <exclude>**/*.xml</exclude>
+              <exclude>*.zargo</exclude>
+              <exclude>**/*.zargo</exclude>
+            </excludes>
+          </imageResource>
+          <formats>
+            <format>
+              <formatName>pdf</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+              <finalName>teiid_quick_start_example.pdf</finalName>
+            </format>
+            <format>
+              <formatName>html_single</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+            <format>
+              <formatName>html</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+          </formats>
+          <options>
+            <xincludeSupported>true</xincludeSupported>
+            <xmlTransformerType>saxon</xmlTransformerType>  
+            <docbookVersion>1.72.0</docbookVersion>              
+            <localeSeparator>-</localeSeparator>
+            <useRelativeImageUris>false</useRelativeImageUris>
+          </options>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/documentation/reference/pom.xml
===================================================================
--- branches/7.2.x/documentation/reference/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/documentation/reference/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
-  <parent>
-    <groupId>org.jboss.teiid</groupId>
-    <artifactId>documentation</artifactId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>reference</artifactId>
-  <groupId>org.jboss.teiid.documentation</groupId>
-  <packaging>jdocbook</packaging>
-  <name>Teiid Reference</name>
-  <description>The Teiid reference manual</description>
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.jboss.maven.plugins</groupId>
-        <artifactId>maven-jdocbook-plugin</artifactId>
-        <version>2.1.2</version>
-        <extensions>true</extensions>
-        <dependencies>
-          <dependency>
-            <groupId>net.sf.docbook</groupId>
-            <artifactId>docbook</artifactId>
-            <version>1.74.0</version>
-          </dependency>         
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-docbook-xslt</artifactId>
-            <version>1.1.0</version>
-          </dependency>
-          <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossorg-jdocbook-style</artifactId>
-            <version>1.1.0</version>
-            <type>jdocbook-style</type>
-          </dependency>
-        </dependencies>
-        <configuration>
-          <sourceDocumentName>Reference.xml</sourceDocumentName>
-          <imageResource>
-            <directory>${basedir}/src/main/docbook/en-US</directory>
-            <excludes>
-              <exclude>*.xml</exclude>
-              <exclude>**/*.xml</exclude>
-              <exclude>*.zargo</exclude>
-              <exclude>**/*.zargo</exclude>
-            </excludes>
-          </imageResource>
-          <formats>
-            <format>
-              <formatName>pdf</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
-              <finalName>teiid_reference.pdf</finalName>
-            </format>
-            <format>
-              <formatName>html_single</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-            <format>
-              <formatName>html</formatName>
-              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
-              <finalName>index.html</finalName>
-            </format>
-          </formats>
-          <options>
-            <xmlTransformerType>saxon</xmlTransformerType>  
-            <docbookVersion>1.72.0</docbookVersion>               
-            <xincludeSupported>true</xincludeSupported>
-            <localeSeparator>-</localeSeparator>
-            <useRelativeImageUris>false</useRelativeImageUris>
-          </options>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/documentation/reference/pom.xml (from rev 2708, branches/7.2.x/documentation/reference/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/documentation/reference/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/documentation/reference/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+  <parent>
+    <groupId>org.jboss.teiid</groupId>
+    <artifactId>documentation</artifactId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>reference</artifactId>
+  <groupId>org.jboss.teiid.documentation</groupId>
+  <packaging>jdocbook</packaging>
+  <name>Teiid Reference</name>
+  <description>The Teiid reference manual</description>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.jboss.maven.plugins</groupId>
+        <artifactId>maven-jdocbook-plugin</artifactId>
+        <version>2.1.2</version>
+        <extensions>true</extensions>
+        <dependencies>
+          <dependency>
+            <groupId>net.sf.docbook</groupId>
+            <artifactId>docbook</artifactId>
+            <version>1.74.0</version>
+          </dependency>         
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-docbook-xslt</artifactId>
+            <version>1.1.0</version>
+          </dependency>
+          <dependency>
+            <groupId>org.jboss</groupId>
+            <artifactId>jbossorg-jdocbook-style</artifactId>
+            <version>1.1.0</version>
+            <type>jdocbook-style</type>
+          </dependency>
+        </dependencies>
+        <configuration>
+          <sourceDocumentName>Reference.xml</sourceDocumentName>
+          <imageResource>
+            <directory>${basedir}/src/main/docbook/en-US</directory>
+            <excludes>
+              <exclude>*.xml</exclude>
+              <exclude>**/*.xml</exclude>
+              <exclude>*.zargo</exclude>
+              <exclude>**/*.zargo</exclude>
+            </excludes>
+          </imageResource>
+          <formats>
+            <format>
+              <formatName>pdf</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+              <finalName>teiid_reference.pdf</finalName>
+            </format>
+            <format>
+              <formatName>html_single</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+            <format>
+              <formatName>html</formatName>
+              <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+              <finalName>index.html</finalName>
+            </format>
+          </formats>
+          <options>
+            <xmlTransformerType>saxon</xmlTransformerType>  
+            <docbookVersion>1.72.0</docbookVersion>               
+            <xincludeSupported>true</xincludeSupported>
+            <localeSeparator>-</localeSeparator>
+            <useRelativeImageUris>false</useRelativeImageUris>
+          </options>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/engine/pom.xml
===================================================================
--- branches/7.2.x/engine/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,97 +0,0 @@
-<?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">
-	<parent>
-		<artifactId>teiid-parent</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>teiid-engine</artifactId>
-	<name>Engine</name>
-	<description>Relational, procedural, and xml core engine.</description>
-
-	<build>
-		<plugins>
-			<plugin>
-				<groupId>org.codehaus.mojo</groupId>
-				<artifactId>javacc-maven-plugin</artifactId>
-				<version>2.4</version>
-				<executions>
-					<execution>
-						<id>javacc</id>
-						<goals>
-							<goal>javacc</goal>
-						</goals>
-					</execution>
-				</executions>
-			</plugin>
-		</plugins>
-	</build>
-
-	<dependencies>
-
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-			<type>test-jar</type>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-api</artifactId>
-			<scope>provided</scope>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-			<scope>provided</scope>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-			<type>test-jar</type>
-		</dependency>
-
-		<dependency>
-			<groupId>javax.resource</groupId>
-			<artifactId>connector-api</artifactId>
-		</dependency>
-
-		<dependency>
-			<groupId>javax.transaction</groupId>
-                <artifactId>jta</artifactId>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.deployers</groupId>
-			<artifactId>jboss-deployers-vfs-spi</artifactId>
-			<scope>provided</scope>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.deployers</groupId>
-			<artifactId>jboss-deployers-vfs</artifactId>
-			<scope>provided</scope>
-		</dependency>
-
-		<dependency>
-			<groupId>net.sourceforge.saxon</groupId>
-			<artifactId>saxon</artifactId>
-		</dependency>
-
-		<dependency>
-			<groupId>net.sourceforge.saxon</groupId>
-			<classifier>dom</classifier>
-			<artifactId>saxon</artifactId>
-		</dependency>
-		
-		<dependency>
-			<groupId>com.googlecode.json-simple</groupId>
-			<artifactId>json-simple</artifactId>
-		</dependency>
-
-	</dependencies>
-
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/engine/pom.xml (from rev 2708, branches/7.2.x/engine/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,97 @@
+<?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">
+	<parent>
+		<artifactId>teiid-parent</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>teiid-engine</artifactId>
+	<name>Engine</name>
+	<description>Relational, procedural, and xml core engine.</description>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.codehaus.mojo</groupId>
+				<artifactId>javacc-maven-plugin</artifactId>
+				<version>2.4</version>
+				<executions>
+					<execution>
+						<id>javacc</id>
+						<goals>
+							<goal>javacc</goal>
+						</goals>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+
+	<dependencies>
+
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-common-core</artifactId>
+			<type>test-jar</type>
+		</dependency>
+
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-api</artifactId>
+			<scope>provided</scope>
+		</dependency>
+
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-client</artifactId>
+			<scope>provided</scope>
+		</dependency>
+
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-client</artifactId>
+			<type>test-jar</type>
+		</dependency>
+
+		<dependency>
+			<groupId>javax.resource</groupId>
+			<artifactId>connector-api</artifactId>
+		</dependency>
+
+		<dependency>
+			<groupId>javax.transaction</groupId>
+                <artifactId>jta</artifactId>
+		</dependency>
+
+		<dependency>
+			<groupId>org.jboss.deployers</groupId>
+			<artifactId>jboss-deployers-vfs-spi</artifactId>
+			<scope>provided</scope>
+		</dependency>
+
+		<dependency>
+			<groupId>org.jboss.deployers</groupId>
+			<artifactId>jboss-deployers-vfs</artifactId>
+			<scope>provided</scope>
+		</dependency>
+
+		<dependency>
+			<groupId>net.sourceforge.saxon</groupId>
+			<artifactId>saxon</artifactId>
+		</dependency>
+
+		<dependency>
+			<groupId>net.sourceforge.saxon</groupId>
+			<classifier>dom</classifier>
+			<artifactId>saxon</artifactId>
+		</dependency>
+		
+		<dependency>
+			<groupId>com.googlecode.json-simple</groupId>
+			<artifactId>json-simple</artifactId>
+		</dependency>
+
+	</dependencies>
+
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/cache/CacheConfiguration.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/cache/CacheConfiguration.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/cache/CacheConfiguration.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,110 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.cache;
-
-public class CacheConfiguration {
-	
-	public static CacheConfiguration DEFAULT = new CacheConfiguration(Policy.LRU, 60*60, 100); // 1 hours with 100 nodes.
-		
-	public enum Policy {
-		LRU,  // Least Recently Used
-		EXPIRATION
-	}
-	
-	private Policy policy;
-	private int maxage;
-	private int maxEntries;
-	private boolean enabled = true;
-	
-	public CacheConfiguration() {
-	}
-	
-	public CacheConfiguration(Policy policy, int maxAgeInSeconds, int maxNodes) {
-		this.policy = policy;
-		this.maxage = maxAgeInSeconds;
-		this.maxEntries = maxNodes;
-	}
-	
-	public Policy getPolicy() {
-		return this.policy;
-	}
-	
-	public int getMaxAgeInSeconds(){
-		return maxage;
-	}
-
-	public void setMaxAgeInSeconds(int maxage){
-		this.maxage = maxage;
-	}
-	
-	public int getMaxEntries() {
-		return this.maxEntries;
-	}
-
-	public void setMaxEntries(int entries) {
-		this.maxEntries = entries;
-	}
-
-	public void setType (String type) {
-		this.policy = Policy.valueOf(type);
-	}
-	
-	@Override
-	public int hashCode() {
-		final int prime = 31;
-		int result = 1;
-		result = prime * result + maxage;
-		result = prime * result + maxEntries;
-		result = prime * result + ((policy == null) ? 0 : policy.hashCode());
-		return result;
-	}
-
-	@Override
-	public boolean equals(Object obj) {
-		if (this == obj)
-			return true;
-		if (obj == null)
-			return false;
-		if (getClass() != obj.getClass())
-			return false;
-		CacheConfiguration other = (CacheConfiguration) obj;
-		if (maxage != other.maxage)
-			return false;
-		if (maxEntries != other.maxEntries)
-			return false;
-		if (policy == null) {
-			if (other.policy != null)
-				return false;
-		} else if (!policy.equals(other.policy))
-			return false;
-		return true;
-	}
-
-	public boolean isEnabled() {
-		return enabled;
-	}
-
-	public void setEnabled(boolean enabled) {
-		this.enabled = enabled;
-	}
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/cache/CacheConfiguration.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/cache/CacheConfiguration.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/cache/CacheConfiguration.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/cache/CacheConfiguration.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,130 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.cache;
+
+import org.jboss.managed.api.annotation.ManagementComponent;
+import org.jboss.managed.api.annotation.ManagementObject;
+import org.jboss.managed.api.annotation.ManagementObjectID;
+import org.jboss.managed.api.annotation.ManagementProperties;
+import org.jboss.managed.api.annotation.ManagementProperty;
+
+ at ManagementObject(componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
+public class CacheConfiguration {
+	
+	public static CacheConfiguration DEFAULT = new CacheConfiguration(Policy.LRU, 60*60, 100); // 1 hours with 100 nodes.
+		
+	public enum Policy {
+		LRU,  // Least Recently Used
+		EXPIRATION
+	}
+	
+	private Policy policy;
+	private int maxage;
+	private int maxEntries;
+	private boolean enabled = true;
+	private String name;
+	
+	public CacheConfiguration() {
+	}
+	
+	public CacheConfiguration(Policy policy, int maxAgeInSeconds, int maxNodes) {
+		this.policy = policy;
+		this.maxage = maxAgeInSeconds;
+		this.maxEntries = maxNodes;
+	}
+	
+	public Policy getPolicy() {
+		return this.policy;
+	}
+
+	@ManagementProperty(description="The maximum age of a result set cache entry in seconds. -1 indicates no max. (default 7200)")
+	public int getMaxAgeInSeconds(){
+		return maxage;
+	}
+
+	public void setMaxAgeInSeconds(int maxage){
+		this.maxage = maxage;
+	}
+	
+	@ManagementProperty(description="The maximum number of result set cache entries. -1 indicates no limit. (default 1024)")
+	public int getMaxEntries() {
+		return this.maxEntries;
+	}
+
+	public void setMaxEntries(int entries) {
+		this.maxEntries = entries;
+	}
+
+	public void setType (String type) {
+		this.policy = Policy.valueOf(type);
+	}
+	
+	@ManagementProperty(description="Name of the configuration", readOnly=true)
+	@ManagementObjectID(type="cache")	
+	public String getName() {
+		return this.name;
+	}
+	
+	public void setName(String name) {
+		this.name = name;
+	}
+	
+	@Override
+	public int hashCode() {
+		final int prime = 31;
+		int result = 1;
+		result = prime * result + maxage;
+		result = prime * result + maxEntries;
+		result = prime * result + ((policy == null) ? 0 : policy.hashCode());
+		return result;
+	}
+
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj)
+			return true;
+		if (obj == null)
+			return false;
+		if (getClass() != obj.getClass())
+			return false;
+		CacheConfiguration other = (CacheConfiguration) obj;
+		if (maxage != other.maxage)
+			return false;
+		if (maxEntries != other.maxEntries)
+			return false;
+		if (policy == null) {
+			if (other.policy != null)
+				return false;
+		} else if (!policy.equals(other.policy))
+			return false;
+		return true;
+	}
+
+	public boolean isEnabled() {
+		return enabled;
+	}
+
+	public void setEnabled(boolean enabled) {
+		this.enabled = enabled;
+	}
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,187 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.dqp.internal.process;
-
-import org.jboss.managed.api.annotation.ManagementProperty;
-import org.teiid.cache.CacheConfiguration;
-import org.teiid.client.RequestMessage;
-import org.teiid.core.util.ApplicationInfo;
-
-
-public class DQPConfiguration{
-	
-    //Constants
-    static final int DEFAULT_FETCH_SIZE = RequestMessage.DEFAULT_FETCH_SIZE * 10;
-    static final int DEFAULT_PROCESSOR_TIMESLICE = 2000;
-    static final int DEFAULT_MAX_RESULTSET_CACHE_ENTRIES = 1024;
-    static final int DEFAULT_QUERY_THRESHOLD = 600;
-    static final String PROCESS_PLAN_QUEUE_NAME = "QueryProcessorQueue"; //$NON-NLS-1$
-    public static final int DEFAULT_MAX_PROCESS_WORKERS = 64;
-	public static final int DEFAULT_MAX_SOURCE_ROWS = -1;
-	public static final int DEFAULT_MAX_ACTIVE_PLANS = 20;
-    
-	private int maxThreads = DEFAULT_MAX_PROCESS_WORKERS;
-	private int timeSliceInMilli = DEFAULT_PROCESSOR_TIMESLICE;
-	private int maxRowsFetchSize = DEFAULT_FETCH_SIZE;
-	private int lobChunkSizeInKB = 100;
-	private int preparedPlanCacheMaxCount = SessionAwareCache.DEFAULT_MAX_SIZE_TOTAL;
-	private boolean useDataRoles = false;
-	private int queryThresholdInSecs = DEFAULT_QUERY_THRESHOLD;
-	private boolean exceptionOnMaxSourceRows = true;
-	private int maxSourceRows = -1;
-	private int maxActivePlans = DEFAULT_MAX_ACTIVE_PLANS;
-	private CacheConfiguration resultsetCacheConfig;
-
-	@ManagementProperty(description="Max active plans (default 20).  Increase this value, and max threads, on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts.")
-	public int getMaxActivePlans() {
-		return maxActivePlans;
-	}
-	
-	public void setMaxActivePlans(int maxActivePlans) {
-		this.maxActivePlans = maxActivePlans;
-	}
-	
-	@ManagementProperty(description="Process pool maximum thread count. (default 64)")
-	public int getMaxThreads() {
-		return maxThreads;
-	}
-
-	public void setMaxThreads(int maxThreads) {
-		this.maxThreads = maxThreads;
-	}
-
-	@ManagementProperty(description="Query processor time slice, in milliseconds. (default 2000)")
-	public int getTimeSliceInMilli() {
-		return timeSliceInMilli;
-	}
-
-	public void setTimeSliceInMilli(int timeSliceInMilli) {
-		this.timeSliceInMilli = timeSliceInMilli;
-	}
-	
-	@ManagementProperty(description="Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480)")
-	public int getMaxRowsFetchSize() {
-		return maxRowsFetchSize;
-	}
-
-	public void setMaxRowsFetchSize(int maxRowsFetchSize) {
-		this.maxRowsFetchSize = maxRowsFetchSize;
-	}
-
-	@ManagementProperty(description="The max lob chunk size in KB transferred to the client for xml, blobs, clobs (default 100KB)")
-	public int getLobChunkSizeInKB() {
-		return this.lobChunkSizeInKB;
-	}
-
-	public void setLobChunkSizeInKB(int lobChunkSizeInKB) {
-		this.lobChunkSizeInKB = lobChunkSizeInKB;
-	}
-
-	@ManagementProperty(description="The maximum number of query plans that are cached. Note: this is a memory based cache. (default 250)")
-	public int getPreparedPlanCacheMaxCount() {
-		return this.preparedPlanCacheMaxCount;
-	}
-
-	public void setPreparedPlanCacheMaxCount(int preparedPlanCacheMaxCount) {
-		this.preparedPlanCacheMaxCount = preparedPlanCacheMaxCount;
-	}
-
-	@ManagementProperty(description="The maximum number of result set cache entries. -1 indicates no limit. (default 1024)")
-	public int getResultSetCacheMaxEntries() {
-		return this.resultsetCacheConfig.getMaxEntries();
-	}
-	
-	public CacheConfiguration getResultsetCacheConfig() {
-		return this.resultsetCacheConfig;
-	}	
-	
-	public void setResultsetCacheConfig(CacheConfiguration config) {
-		this.resultsetCacheConfig = config;
-	}
-	
-	@ManagementProperty(description="Denotes whether or not result set caching is enabled. (default true)")
-	public boolean isResultSetCacheEnabled() {
-		return this.resultsetCacheConfig.isEnabled();
-	}
-	
-	@ManagementProperty(description="The maximum age of a result set cache entry in seconds. -1 indicates no max. (default 7200)")
-	public int getResultSetCacheMaxEntryAge() {
-		return this.resultsetCacheConfig.getMaxAgeInSeconds();
-	}
-	
-	public void setResultSetCacheMaxEntryAge(int maxAge) {
-		this.resultsetCacheConfig.setMaxAgeInSeconds(maxAge);
-	}
-	
-    /**
-     * Determine whether role checking is enabled on the server.
-     * @return <code>true</code> if server-side role checking is enabled.
-     */
-    @ManagementProperty(description="Turn on role checking on resources based on the roles defined in VDB")
-    public boolean useDataRoles() {
-        return useDataRoles;
-    }
-
-	public void setUseDataRoles(Boolean useEntitlements) {
-		this.useDataRoles = useEntitlements.booleanValue();
-	}
-
-	@ManagementProperty(description="Long running query threshold, after which a alert can be generated by tooling if configured")
-	public int getQueryThresholdInSecs() {
-		return queryThresholdInSecs;
-	}
-
-	public void setQueryThresholdInSecs(int queryThresholdInSecs) {
-		this.queryThresholdInSecs = queryThresholdInSecs;
-	}
-	
-	@ManagementProperty(description="Teiid runtime version", readOnly=true)
-	public String getRuntimeVersion() {
-		return ApplicationInfo.getInstance().getBuildNumber();
-	}
-	
-	/**
-	 * Throw exception if there are more rows in the result set than specified in the MaxSourceRows setting.
-	 * @return
-	 */
-	@ManagementProperty(description="Indicates if an exception should be thrown if the specified value for Maximum Source Rows is exceeded; only up to the maximum rows will be consumed.")
-	public boolean isExceptionOnMaxSourceRows() {
-		return exceptionOnMaxSourceRows;
-	}
-	
-	public void setExceptionOnMaxSourceRows(boolean exceptionOnMaxSourceRows) {
-		this.exceptionOnMaxSourceRows = exceptionOnMaxSourceRows;
-	}
-
-	/**
-	 * Maximum source set rows to fetch
-	 * @return
-	 */
-	@ManagementProperty(description="Maximum rows allowed from a source query. -1 indicates no limit. (default -1)")
-	public int getMaxSourceRows() {
-		return maxSourceRows;
-	}
-
-	public void setMaxSourceRows(int maxSourceRows) {
-		this.maxSourceRows = maxSourceRows;
-	}
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,173 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.dqp.internal.process;
+
+import org.jboss.managed.api.annotation.ManagementProperty;
+import org.teiid.cache.CacheConfiguration;
+import org.teiid.client.RequestMessage;
+import org.teiid.core.util.ApplicationInfo;
+
+
+public class DQPConfiguration{
+	
+    //Constants
+    static final int DEFAULT_FETCH_SIZE = RequestMessage.DEFAULT_FETCH_SIZE * 10;
+    static final int DEFAULT_PROCESSOR_TIMESLICE = 2000;
+    static final int DEFAULT_MAX_RESULTSET_CACHE_ENTRIES = 1024;
+    static final int DEFAULT_QUERY_THRESHOLD = 600;
+    static final String PROCESS_PLAN_QUEUE_NAME = "QueryProcessorQueue"; //$NON-NLS-1$
+    public static final int DEFAULT_MAX_PROCESS_WORKERS = 64;
+	public static final int DEFAULT_MAX_SOURCE_ROWS = -1;
+	public static final int DEFAULT_MAX_ACTIVE_PLANS = 20;
+    
+	private int maxThreads = DEFAULT_MAX_PROCESS_WORKERS;
+	private int timeSliceInMilli = DEFAULT_PROCESSOR_TIMESLICE;
+	private int maxRowsFetchSize = DEFAULT_FETCH_SIZE;
+	private int lobChunkSizeInKB = 100;
+	private int preparedPlanCacheMaxCount = SessionAwareCache.DEFAULT_MAX_SIZE_TOTAL;
+	private boolean useDataRoles = false;
+	private int queryThresholdInSecs = DEFAULT_QUERY_THRESHOLD;
+	private boolean exceptionOnMaxSourceRows = true;
+	private int maxSourceRows = -1;
+	private int maxActivePlans = DEFAULT_MAX_ACTIVE_PLANS;
+	private CacheConfiguration resultsetCacheConfig;
+
+	@ManagementProperty(description="Max active plans (default 20).  Increase this value, and max threads, on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts.")
+	public int getMaxActivePlans() {
+		return maxActivePlans;
+	}
+	
+	public void setMaxActivePlans(int maxActivePlans) {
+		this.maxActivePlans = maxActivePlans;
+	}
+	
+	@ManagementProperty(description="Process pool maximum thread count. (default 64)")
+	public int getMaxThreads() {
+		return maxThreads;
+	}
+
+	public void setMaxThreads(int maxThreads) {
+		this.maxThreads = maxThreads;
+	}
+
+	@ManagementProperty(description="Query processor time slice, in milliseconds. (default 2000)")
+	public int getTimeSliceInMilli() {
+		return timeSliceInMilli;
+	}
+
+	public void setTimeSliceInMilli(int timeSliceInMilli) {
+		this.timeSliceInMilli = timeSliceInMilli;
+	}
+	
+	@ManagementProperty(description="Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480)")
+	public int getMaxRowsFetchSize() {
+		return maxRowsFetchSize;
+	}
+
+	public void setMaxRowsFetchSize(int maxRowsFetchSize) {
+		this.maxRowsFetchSize = maxRowsFetchSize;
+	}
+
+	@ManagementProperty(description="The max lob chunk size in KB transferred to the client for xml, blobs, clobs (default 100KB)")
+	public int getLobChunkSizeInKB() {
+		return this.lobChunkSizeInKB;
+	}
+
+	public void setLobChunkSizeInKB(int lobChunkSizeInKB) {
+		this.lobChunkSizeInKB = lobChunkSizeInKB;
+	}
+
+	@ManagementProperty(description="The maximum number of query plans that are cached. Note: this is a memory based cache. (default 250)")
+	public int getPreparedPlanCacheMaxCount() {
+		return this.preparedPlanCacheMaxCount;
+	}
+
+	public void setPreparedPlanCacheMaxCount(int preparedPlanCacheMaxCount) {
+		this.preparedPlanCacheMaxCount = preparedPlanCacheMaxCount;
+	}
+	
+	public CacheConfiguration getResultsetCacheConfig() {
+		return this.resultsetCacheConfig;
+	}	
+	
+	public void setResultsetCacheConfig(CacheConfiguration config) {
+		this.resultsetCacheConfig = config;
+	}
+	
+	@ManagementProperty(description="Denotes whether or not result set caching is enabled. (default true)")
+	public boolean isResultSetCacheEnabled() {
+		return this.resultsetCacheConfig != null && this.resultsetCacheConfig.isEnabled();
+	}
+	
+    /**
+     * Determine whether role checking is enabled on the server.
+     * @return <code>true</code> if server-side role checking is enabled.
+     */
+    @ManagementProperty(description="Turn on role checking on resources based on the roles defined in VDB")
+    public boolean getUseDataRoles() {
+        return useDataRoles;
+    }
+
+	public void setUseDataRoles(boolean useEntitlements) {
+		this.useDataRoles = useEntitlements;
+	}
+
+	@ManagementProperty(description="Long running query threshold, after which a alert can be generated by tooling if configured")
+	public int getQueryThresholdInSecs() {
+		return queryThresholdInSecs;
+	}
+
+	public void setQueryThresholdInSecs(int queryThresholdInSecs) {
+		this.queryThresholdInSecs = queryThresholdInSecs;
+	}
+	
+	@ManagementProperty(description="Teiid runtime version", readOnly=true)
+	public String getRuntimeVersion() {
+		return ApplicationInfo.getInstance().getBuildNumber();
+	}
+	
+	/**
+	 * Throw exception if there are more rows in the result set than specified in the MaxSourceRows setting.
+	 * @return
+	 */
+	@ManagementProperty(description="Indicates if an exception should be thrown if the specified value for Maximum Source Rows is exceeded; only up to the maximum rows will be consumed.")
+	public boolean isExceptionOnMaxSourceRows() {
+		return exceptionOnMaxSourceRows;
+	}
+	
+	public void setExceptionOnMaxSourceRows(boolean exceptionOnMaxSourceRows) {
+		this.exceptionOnMaxSourceRows = exceptionOnMaxSourceRows;
+	}
+
+	/**
+	 * Maximum source set rows to fetch
+	 * @return
+	 */
+	@ManagementProperty(description="Maximum rows allowed from a source query. -1 indicates no limit. (default -1)")
+	public int getMaxSourceRows() {
+		return maxSourceRows;
+	}
+
+	public void setMaxSourceRows(int maxSourceRows) {
+		this.maxSourceRows = maxSourceRows;
+	}
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,867 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.dqp.internal.process;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
-
-import javax.resource.spi.work.Work;
-import javax.resource.spi.work.WorkEvent;
-import javax.resource.spi.work.WorkListener;
-import javax.transaction.xa.Xid;
-
-import org.teiid.adminapi.Admin;
-import org.teiid.adminapi.AdminException;
-import org.teiid.adminapi.Request.ProcessingState;
-import org.teiid.adminapi.Request.ThreadState;
-import org.teiid.adminapi.impl.CacheStatisticsMetadata;
-import org.teiid.adminapi.impl.RequestMetadata;
-import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
-import org.teiid.cache.Cache;
-import org.teiid.cache.CacheConfiguration;
-import org.teiid.cache.CacheFactory;
-import org.teiid.cache.CacheConfiguration.Policy;
-import org.teiid.client.DQP;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.client.lob.LobChunk;
-import org.teiid.client.metadata.MetadataResult;
-import org.teiid.client.util.ResultsFuture;
-import org.teiid.client.util.ResultsReceiver;
-import org.teiid.client.xa.XATransactionException;
-import org.teiid.client.xa.XidImpl;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.Streamable;
-import org.teiid.dqp.internal.process.ThreadReuseExecutor.PrioritizedRunnable;
-import org.teiid.dqp.message.AtomicRequestMessage;
-import org.teiid.dqp.message.RequestID;
-import org.teiid.dqp.service.BufferService;
-import org.teiid.dqp.service.TransactionContext;
-import org.teiid.dqp.service.TransactionService;
-import org.teiid.dqp.service.TransactionContext.Scope;
-import org.teiid.logging.CommandLogMessage;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.logging.MessageLevel;
-import org.teiid.logging.CommandLogMessage.Event;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.tempdata.TempTableDataManager;
-import org.teiid.query.tempdata.TempTableStore;
-
-
-/**
- * Implements the core DQP processing.
- */
-public class DQPCore implements DQP {
-	
-	//TODO: replace with FutureTask
-	public final static class FutureWork<T> implements Work, WorkListener, PrioritizedRunnable {
-		private final Callable<T> toCall;
-		private ResultsFuture<T> result = new ResultsFuture<T>();
-		private ResultsReceiver<T> receiver = result.getResultsReceiver();
-		private int priority;
-		private long creationTime = System.currentTimeMillis();
-		private DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-
-		public FutureWork(Callable<T> processor, int priority) {
-			this.toCall = processor;
-			this.priority = priority;
-		}
-		
-		public ResultsFuture<T> getResult() {
-			return result;
-		}
-		
-		@Override
-		public void run() {
-			try {
-				receiver.receiveResults(toCall.call());
-			} catch (Throwable t) {
-				receiver.exceptionOccurred(t);
-			}
-		}
-
-		@Override
-		public void release() {
-			
-		}
-		
-		@Override
-		public void workAccepted(WorkEvent arg0) {
-			
-		}
-		
-		@Override
-		public void workCompleted(WorkEvent arg0) {
-			
-		}
-		
-		@Override
-		public void workRejected(WorkEvent arg0) {
-			receiver.exceptionOccurred(arg0.getException());
-		}
-		
-		@Override
-		public void workStarted(WorkEvent arg0) {
-			
-		}
-
-		@Override
-		public int getPriority() {
-			return priority;
-		}
-		
-		@Override
-		public long getCreationTime() {
-			return creationTime;
-		}
-		
-		@Override
-		public DQPWorkContext getDqpWorkContext() {
-			return workContext;
-		}
-	}	
-	
-	static class ClientState {
-		List<RequestID> requests;
-		TempTableStore sessionTables;
-		
-		public ClientState(TempTableStore tableStoreImpl) {
-			this.sessionTables = tableStoreImpl;
-		}
-		
-		public synchronized void addRequest(RequestID requestID) {
-			if (requests == null) {
-				requests = new LinkedList<RequestID>();
-			}
-			requests.add(requestID);
-		}
-		
-		public synchronized List<RequestID> getRequests() {
-			if (requests == null) {
-				return Collections.emptyList();
-			}
-			return new ArrayList<RequestID>(requests);
-		}
-
-		public synchronized void removeRequest(RequestID requestID) {
-			if (requests != null) {
-				requests.remove(requestID);
-			}
-		}
-		
-	}
-	
-	private ThreadReuseExecutor processWorkerPool;
-    
-    private int maxFetchSize = DQPConfiguration.DEFAULT_FETCH_SIZE;
-    private int queryThreshold = DQPConfiguration.DEFAULT_QUERY_THRESHOLD;
-    
-    // Resources
-    private BufferManager bufferManager;
-    private ProcessorDataManager dataTierMgr;
-    private SessionAwareCache<PreparedPlan> prepPlanCache;
-    private SessionAwareCache<CachedResults> rsCache;
-    private TransactionService transactionService;
-    private BufferService bufferService;
-    
-    // Query worker pool for processing plans
-    private int processorTimeslice = DQPConfiguration.DEFAULT_PROCESSOR_TIMESLICE;
-    
-    private int maxSourceRows = DQPConfiguration.DEFAULT_MAX_SOURCE_ROWS;
-    private boolean exceptionOnMaxSourceRows = true;
-    
-    private int chunkSize = Streamable.STREAMING_BATCH_SIZE_IN_BYTES;
-    
-	private Map<RequestID, RequestWorkItem> requests = new ConcurrentHashMap<RequestID, RequestWorkItem>();			
-	private Map<String, ClientState> clientState = new ConcurrentHashMap<String, ClientState>();
-    private boolean useEntitlements = false;
-    
-    private int maxActivePlans = DQPConfiguration.DEFAULT_MAX_ACTIVE_PLANS;
-    private int currentlyActivePlans;
-    private LinkedList<RequestWorkItem> waitingPlans = new LinkedList<RequestWorkItem>();
-    private CacheFactory cacheFactory;
-
-	private SessionAwareCache<CachedResults> matTables;
-    
-    /**
-     * perform a full shutdown and wait for 10 seconds for all threads to finish
-     */
-    public void stop() {
-    	processWorkerPool.shutdownNow();
-    	try {
-			processWorkerPool.awaitTermination(10, TimeUnit.SECONDS);
-		} catch (InterruptedException e) {
-		}
-    	// TODO: Should we be doing more cleanup here??
-		LogManager.logDetail(LogConstants.CTX_DQP, "Stopping the DQP"); //$NON-NLS-1$
-    }
-    
-    /**
-     * Return a list of {@link RequestMetadata} for the given session
-     */
-    public List<RequestMetadata> getRequestsForSession(String sessionId) {
-    	ClientState state = getClientState(sessionId, false);
-    	if (state == null) {
-    		return Collections.emptyList();
-    	}
-        return buildRequestInfos(state.getRequests(), -1);
-    }
-    
-    public ClientState getClientState(String key, boolean create) {
-    	if (key == null) {
-    		return null;
-    	}
-		ClientState state = clientState.get(key);
-		if (state == null && create) {
-			state = new ClientState(new TempTableStore(key));
-    		clientState.put(key, state);
-		}
-		return state;
-    }
-
-    /**
-     * Return a list of all {@link RequestMetadata} 
-     */
-    public List<RequestMetadata> getRequests() {
-		return buildRequestInfos(requests.keySet(), -1);
-    } 
-    
-    public List<RequestMetadata> getLongRunningRequests(){
-    	return buildRequestInfos(requests.keySet(), this.queryThreshold);
-    }
-
-    private List<RequestMetadata> buildRequestInfos(Collection<RequestID> ids, int longRunningQueryThreshold) {
-		List<RequestMetadata> results = new ArrayList<RequestMetadata>();
-    	
-		for (RequestID requestID : ids) {
-            RequestWorkItem holder = requests.get(requestID);
-            
-            if(holder != null && !holder.isCanceled()) {
-            	RequestMetadata req = new RequestMetadata();
-            	
-            	req.setExecutionId(holder.requestID.getExecutionID());
-            	req.setSessionId(holder.requestID.getConnectionID());
-            	req.setCommand(holder.requestMsg.getCommandString());
-            	req.setStartTime(holder.getProcessingTimestamp());
-            	req.setState(holder.isCanceled()?ProcessingState.CANCELED:holder.isDoneProcessing()?ProcessingState.DONE:ProcessingState.PROCESSING);
-            	switch (holder.getThreadState()) {
-            	case DONE:
-            	case IDLE:
-            		req.setThreadState(ThreadState.IDLE);
-            		break;
-            	default:
-            		if (holder.isProcessing()) {
-            			req.setThreadState(ThreadState.RUNNING);
-            		} else {
-            			req.setThreadState(ThreadState.QUEUED);
-            		}
-            	}
-            	if (holder.getTransactionContext() != null && holder.getTransactionContext().getTransactionType() != Scope.NONE) {
-            		req.setTransactionId(holder.getTransactionContext().getTransactionId());
-            	}
-
-                for (DataTierTupleSource conInfo : holder.getConnectorRequests()) {
-                    String connectorName = conInfo.getConnectorName();
-
-                    if (connectorName == null) {
-                    	continue;
-                    }
-                    // If the request has not yet completed processing, then
-                    // add all the subrequest messages
-                	AtomicRequestMessage arm = conInfo.getAtomicRequestMessage();
-                	RequestMetadata info = new RequestMetadata();
-                	if (conInfo.isQueued()) {
-                		info.setThreadState(ThreadState.QUEUED);
-                	} else if (conInfo.isRunning()) {
-                		info.setThreadState(ThreadState.RUNNING);
-                	} else {
-                		info.setThreadState(ThreadState.IDLE);
-                	}
-                	info.setExecutionId(arm.getRequestID().getExecutionID());
-                	info.setSessionId(holder.requestID.getConnectionID());
-                	info.setCommand(arm.getCommand().toString());
-                	info.setStartTime(arm.getProcessingTimestamp());
-                	info.setSourceRequest(true);
-                	info.setNodeId(arm.getAtomicRequestID().getNodeID());
-                	info.setState(conInfo.isCanceled()?ProcessingState.CANCELED:conInfo.isDone()?ProcessingState.DONE:ProcessingState.PROCESSING);
-        			results.add(info);
-                }
-                
-                // check if only need long running queries.
-                long elapsedTime = System.currentTimeMillis() - req.getStartTime();
-                if (longRunningQueryThreshold == -1 || elapsedTime > longRunningQueryThreshold) {
-                	results.add(req);
-                }
-            }
-        }
-    	return results;
-	}    
-
-	public ResultsFuture<ResultsMessage> executeRequest(long reqID,RequestMessage requestMsg) {
-    	DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-		RequestID requestID = workContext.getRequestID(reqID);
-		requestMsg.setFetchSize(Math.min(requestMsg.getFetchSize(), maxFetchSize));
-		Request request = null;
-	    if ( requestMsg.isPreparedStatement() || requestMsg.isCallableStatement()) {
-	    	request = new PreparedStatementRequest(prepPlanCache);
-	    } else {
-	    	request = new Request();
-	    }
-	    ClientState state = this.getClientState(workContext.getSessionId(), true);
-	    request.initialize(requestMsg, bufferManager,
-				dataTierMgr, transactionService, state.sessionTables,
-				workContext, this.useEntitlements, this.prepPlanCache);
-		request.setResultSetCacheEnabled(this.rsCache != null);
-        ResultsFuture<ResultsMessage> resultsFuture = new ResultsFuture<ResultsMessage>();
-        RequestWorkItem workItem = new RequestWorkItem(this, requestMsg, request, resultsFuture.getResultsReceiver(), requestID, workContext);
-    	logMMCommand(workItem, Event.NEW, null); 
-        addRequest(requestID, workItem, state);
-        synchronized (waitingPlans) {
-			if (currentlyActivePlans < maxActivePlans) {
-				startActivePlan(workItem);
-			} else {
-				if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-		            LogManager.logDetail(LogConstants.CTX_DQP, "Queuing plan, since max plans has been reached.");  //$NON-NLS-1$
-		        }  
-				waitingPlans.add(workItem);
-			}
-		}
-        return resultsFuture;
-    }
-	
-	public ResultsFuture<ResultsMessage> processCursorRequest(long reqID,
-			int batchFirst, int fetchSize) throws TeiidProcessingException {
-        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-            LogManager.logDetail(LogConstants.CTX_DQP, "DQP process cursor request from " + batchFirst);  //$NON-NLS-1$
-        }
-		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-        ResultsFuture<ResultsMessage> resultsFuture = new ResultsFuture<ResultsMessage>();
-		RequestWorkItem workItem = getRequestWorkItem(workContext.getRequestID(reqID));
-		workItem.requestMore(batchFirst, batchFirst + Math.min(fetchSize, maxFetchSize) - 1, resultsFuture.getResultsReceiver());
-		return resultsFuture;
-	}
-
-	void addRequest(RequestID requestID, RequestWorkItem workItem, ClientState state) {
-		this.requests.put(requestID, workItem);
-		state.addRequest(requestID);
-	}
-
-	private void startActivePlan(RequestWorkItem workItem) {
-		workItem.active = true;
-		this.addWork(workItem);
-		this.currentlyActivePlans++;
-	}
-	
-    void finishProcessing(final RequestWorkItem workItem) {
-    	synchronized (waitingPlans) {
-    		if (!workItem.active) {
-        		return;
-        	}
-        	workItem.active = false;
-    		currentlyActivePlans--;
-			if (!waitingPlans.isEmpty()) {
-				startActivePlan(waitingPlans.remove());
-			}
-		}
-    }
-    
-    void removeRequest(final RequestWorkItem workItem) {
-    	finishProcessing(workItem);
-    	this.requests.remove(workItem.requestID);
-    	ClientState state = getClientState(workItem.getDqpWorkContext().getSessionId(), false);
-    	if (state != null) {
-    		state.removeRequest(workItem.requestID);
-    	}
-    }
-    
-    void addWork(Runnable work) {
-		this.processWorkerPool.execute(work);
-    }
-    
-    void scheduleWork(final Runnable r, int priority, long delay) {
-		this.processWorkerPool.schedule(new FutureWork<Void>(new Callable<Void>() {
-			@Override
-			public Void call() throws Exception {
-				r.run();
-				return null;
-			}
-		}, priority), delay, TimeUnit.MILLISECONDS);
-    }
-    
-	public ResultsFuture<?> closeLobChunkStream(int lobRequestId,
-			long requestId, String streamId)
-			throws TeiidProcessingException {
-        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-            LogManager.logDetail(LogConstants.CTX_DQP, "Request to close the Lob stream with Stream id="+streamId+" instance id="+lobRequestId);  //$NON-NLS-1$//$NON-NLS-2$
-        }   
-        DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-        RequestWorkItem workItem = safeGetWorkItem(workContext.getRequestID(requestId));
-        if (workItem != null) {
-	        workItem.removeLobStream(lobRequestId);
-        }
-        return ResultsFuture.NULL_FUTURE;
-    }
-	    
-	public ResultsFuture<LobChunk> requestNextLobChunk(int lobRequestId,
-			long requestId, String streamId)
-			throws TeiidProcessingException {
-        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-            LogManager.logDetail(LogConstants.CTX_DQP, "Request for next Lob chunk with Stream id="+streamId+" instance id="+lobRequestId);  //$NON-NLS-1$//$NON-NLS-2$
-        }  
-        RequestWorkItem workItem = getRequestWorkItem(DQPWorkContext.getWorkContext().getRequestID(requestId));
-        ResultsFuture<LobChunk> resultsFuture = new ResultsFuture<LobChunk>();
-        workItem.processLobChunkRequest(streamId, lobRequestId, resultsFuture.getResultsReceiver());
-        return resultsFuture;
-    }
-    
-//    /**
-//     * Cancels a node in the request. (This request is called by the 
-//     * client directly using the admin API), so if this does not support
-//     * partial results then remove the original request.
-//     * @throws MetaMatrixComponentException 
-//     */
-//    public void cancelAtomicRequest(AtomicRequestID requestID) throws MetaMatrixComponentException {                    
-//        RequestWorkItem workItem = safeGetWorkItem(requestID.getRequestID());
-//        if (workItem == null) {
-//    		LogManager.logDetail(LogConstants.CTX_DQP, "Could not cancel", requestID, "parent request does not exist"); //$NON-NLS-1$ //$NON-NLS-2$
-//        	return;
-//        }
-//        workItem.requestAtomicRequestCancel(requestID);
-//    }
-    
-    RequestWorkItem getRequestWorkItem(RequestID reqID) throws TeiidProcessingException {
-    	RequestWorkItem result = this.requests.get(reqID);
-    	if (result == null) {
-    		throw new TeiidProcessingException(QueryPlugin.Util.getString("DQPCore.The_request_has_been_closed.", reqID));//$NON-NLS-1$
-    	}
-    	return result;
-    }
-    
-	RequestWorkItem safeGetWorkItem(Object processorID) {
-    	return this.requests.get(processorID);
-	}
-	
-    public WorkerPoolStatisticsMetadata getWorkerPoolStatistics() {
-    	return this.processWorkerPool.getStats();
-    }
-           
-    public void terminateSession(String sessionId) {
-        // sometimes there will not be any atomic requests pending, in that
-        // situation we still need to clear the master request from our map
-        ClientState state = getClientState(sessionId, false);
-        if (state != null) {
-	        for (RequestID reqId : state.getRequests()) {
-	            try {
-	                cancelRequest(reqId);
-	            } catch (TeiidComponentException err) {
-	                LogManager.logWarning(LogConstants.CTX_DQP, err, "Failed to cancel " + reqId); //$NON-NLS-1$
-				}
-	        }
-        }
-        
-        try {
-            transactionService.cancelTransactions(sessionId, false);
-        } catch (XATransactionException err) {
-            LogManager.logWarning(LogConstants.CTX_DQP, "rollback failed for requestID=" + sessionId); //$NON-NLS-1$
-        } 
-    }
-
-    public boolean cancelRequest(String sessionId, long executionId) throws TeiidComponentException {
-    	RequestID requestID = new RequestID(sessionId, executionId);
-    	return cancelRequest(requestID);
-    }
-    
-    private boolean cancelRequest(RequestID requestID) throws TeiidComponentException {
-        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-            LogManager.logDetail(LogConstants.CTX_DQP, "cancelQuery for requestID=" + requestID); //$NON-NLS-1$
-        }
-        
-        boolean markCancelled = false;
-        
-        RequestWorkItem workItem = safeGetWorkItem(requestID);
-        if (workItem != null) {
-        	markCancelled = workItem.requestCancel();
-        }
-    	if (markCancelled) {
-            logMMCommand(workItem, Event.CANCEL, null);
-    	} else {
-    		LogManager.logDetail(LogConstants.CTX_DQP, QueryPlugin.Util.getString("DQPCore.failed_to_cancel")); //$NON-NLS-1$
-    	}
-        return markCancelled;
-    }
-    
-	public ResultsFuture<?> closeRequest(long requestId) throws TeiidProcessingException, TeiidComponentException {
-        DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-        closeRequest(workContext.getRequestID(requestId));
-        return ResultsFuture.NULL_FUTURE;
-	}
-    
-    /**
-     * Close the request with given ID 
-     * @param requestID
-     * @throws TeiidComponentException 
-     */
-    void closeRequest(RequestID requestID) throws TeiidComponentException {
-        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-            LogManager.logDetail(LogConstants.CTX_DQP, "closeQuery for requestID=" + requestID); //$NON-NLS-1$
-        }
-        
-        RequestWorkItem workItem = safeGetWorkItem(requestID);
-        if (workItem != null) {
-        	workItem.requestClose();
-        } else {
-        	LogManager.logDetail(LogConstants.CTX_DQP, requestID + " close call ignored as the request has already been removed."); //$NON-NLS-1$
-        }
-    }
-    
-    private void clearPlanCache(){
-        LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("DQPCore.Clearing_prepared_plan_cache")); //$NON-NLS-1$
-        this.prepPlanCache.clearAll();
-    }
-
-	private void clearResultSetCache() {
-		//clear cache in server
-		if(rsCache != null){
-			rsCache.clearAll();
-		}
-	}
-	
-    private void clearPlanCache(String vdbName, int version){
-        LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("DQPCore.Clearing_prepared_plan_cache")); //$NON-NLS-1$
-        this.prepPlanCache.clearForVDB(vdbName, version);
-    }
-
-	private void clearResultSetCache(String vdbName, int version) {
-		//clear cache in server
-		if(rsCache != null){
-			rsCache.clearForVDB(vdbName, version);
-		}
-	}
-	
-	public CacheStatisticsMetadata getCacheStatistics(String cacheType) {
-		if (cacheType.equalsIgnoreCase(Admin.Cache.PREPARED_PLAN_CACHE.toString())) {
-			return buildCacheStats(Admin.Cache.PREPARED_PLAN_CACHE.toString(), this.prepPlanCache);
-		}
-		else if (cacheType.equalsIgnoreCase(Admin.Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString())) {
-			return buildCacheStats(Admin.Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString(), this.rsCache);
-		}
-		return null;
-	}
-	
-	private CacheStatisticsMetadata buildCacheStats(String name, SessionAwareCache cache) {
-		CacheStatisticsMetadata stats = new CacheStatisticsMetadata();
-		stats.setName(name);
-		stats.setHitRatio(cache.getRequestCount() == 0?0:((double)cache.getCacheHitCount()/cache.getRequestCount())*100);
-		stats.setTotalEntries(cache.getTotalCacheEntries());
-		stats.setRequestCount(cache.getRequestCount());
-		return stats;
-	}
-	
-    public Collection<String> getCacheTypes(){
-    	ArrayList<String> caches = new ArrayList<String>();
-    	caches.add(Admin.Cache.PREPARED_PLAN_CACHE.toString());
-    	caches.add(Admin.Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString());
-    	return caches;
-    }	
-	
-	public void clearCache(String cacheType) {
-		Admin.Cache cache = Admin.Cache.valueOf(cacheType);
-		switch (cache) {
-		case PREPARED_PLAN_CACHE:
-			clearPlanCache();
-			break;
-		case QUERY_SERVICE_RESULT_SET_CACHE:
-			clearResultSetCache();
-			break;
-		}
-	}
-	
-	public void clearCache(String cacheType, String vdbName, int version) {
-		Admin.Cache cache = Admin.Cache.valueOf(cacheType);
-		switch (cache) {
-		case PREPARED_PLAN_CACHE:
-			clearPlanCache(vdbName, version);
-			break;
-		case QUERY_SERVICE_RESULT_SET_CACHE:
-			clearResultSetCache(vdbName, version);
-			break;
-		}
-		if (this.matTables != null) {
-			this.matTables.clearForVDB(vdbName, version);
-		}
-	}	
-    
-	public Collection<org.teiid.adminapi.Transaction> getTransactions() {
-		return this.transactionService.getTransactions();
-	}
-	
-	public void terminateTransaction(String xid) throws AdminException {
-		this.transactionService.terminateTransaction(xid);
-	}	
-	
-    void logMMCommand(RequestWorkItem workItem, Event status, Integer rowCount) {
-    	if (!LogManager.isMessageToBeRecorded(LogConstants.CTX_COMMANDLOGGING, MessageLevel.DETAIL)) {
-    		return;
-    	}
-    	
-        RequestMessage msg = workItem.requestMsg;
-        DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-        RequestID rID = new RequestID(workContext.getSessionId(), msg.getExecutionId());
-    	String txnID = null;
-		TransactionContext tc = workItem.getTransactionContext();
-		if (tc != null && tc.getTransactionType() != Scope.NONE) {
-			txnID = tc.getTransactionId();
-		}
-    	String appName = workContext.getAppName();
-        // Log to request log
-        CommandLogMessage message = null;
-        if (status == Event.NEW) {
-            message = new CommandLogMessage(System.currentTimeMillis(), rID.toString(), txnID, workContext.getSessionId(), appName, workContext.getUserName(), workContext.getVdbName(), workContext.getVdbVersion(), msg.getCommandString());
-        } else {
-            message = new CommandLogMessage(System.currentTimeMillis(), rID.toString(), txnID, workContext.getSessionId(), workContext.getUserName(), workContext.getVdbName(), workContext.getVdbVersion(), rowCount, status);
-        }
-        LogManager.log(MessageLevel.DETAIL, LogConstants.CTX_COMMANDLOGGING, message);
-    }
-    
-    ProcessorDataManager getDataTierManager() {
-    	return this.dataTierMgr;
-    }
-    
-	public BufferManager getBufferManager() {
-		return bufferManager;
-	}
-
-	public TransactionService getTransactionService() {
-		return transactionService;
-	}
-
-	SessionAwareCache<CachedResults> getRsCache() {
-		return rsCache;
-	}
-	
-	int getProcessorTimeSlice() {
-		return this.processorTimeslice;
-	}	
-	
-	int getChunkSize() {
-		return chunkSize;
-	}
-	
-	public void start(DQPConfiguration config) {
-		this.processorTimeslice = config.getTimeSliceInMilli();
-        this.maxFetchSize = config.getMaxRowsFetchSize();
-        this.useEntitlements = config.useDataRoles();
-        this.queryThreshold = config.getQueryThresholdInSecs();
-        this.maxSourceRows = config.getMaxSourceRows();
-        this.exceptionOnMaxSourceRows = config.isExceptionOnMaxSourceRows();
-        
-        this.chunkSize = config.getLobChunkSizeInKB() * 1024;
-
-        //get buffer manager
-        this.bufferManager = bufferService.getBufferManager();
-        
-        //result set cache
-        CacheConfiguration rsCacheConfig = config.getResultsetCacheConfig();
-        if (rsCacheConfig != null && rsCacheConfig.isEnabled()) {
-			this.rsCache = new SessionAwareCache<CachedResults>(this.cacheFactory, Cache.Type.RESULTSET, rsCacheConfig);
-			this.rsCache.setBufferManager(this.bufferManager);
-        }
-
-        //prepared plan cache
-        prepPlanCache = new SessionAwareCache<PreparedPlan>(this.cacheFactory, Cache.Type.PREPAREDPLAN,  new CacheConfiguration(Policy.LRU, 60*60*8, config.getPreparedPlanCacheMaxCount()));
-        prepPlanCache.setBufferManager(this.bufferManager);
-		
-        
-        this.processWorkerPool = new ThreadReuseExecutor(DQPConfiguration.PROCESS_PLAN_QUEUE_NAME, config.getMaxThreads());
-        
-        if (cacheFactory.isReplicated()) {
-        	matTables = new SessionAwareCache<CachedResults>();
-        }
-        
-        dataTierMgr = new TempTableDataManager(new DataTierManagerImpl(this,
-                                            this.bufferService), this.bufferManager, this.processWorkerPool, this.rsCache, matTables, this.cacheFactory); 
-	}
-	
-	public void setBufferService(BufferService service) {
-		this.bufferService = service;
-	}
-	
-	public void setTransactionService(TransactionService service) {
-		this.transactionService = service;
-	}
-	
-	@Override
-	public boolean cancelRequest(long requestID)
-			throws TeiidProcessingException, TeiidComponentException {
-		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-		return this.cancelRequest(workContext.getRequestID(requestID));
-	}
-	
-	// local txn
-	public ResultsFuture<?> begin() throws XATransactionException {
-    	String threadId = DQPWorkContext.getWorkContext().getSessionId();
-    	this.getTransactionService().begin(threadId);
-    	return ResultsFuture.NULL_FUTURE;
-	}
-	
-	// local txn
-	public ResultsFuture<?> commit() throws XATransactionException {
-		final String threadId = DQPWorkContext.getWorkContext().getSessionId();
-		Callable<Void> processor = new Callable<Void>() {
-			@Override
-			public Void call() throws Exception {
-				getTransactionService().commit(threadId);
-				return null;
-			}
-		};
-		return addWork(processor, 0);
-	}
-	
-	// local txn
-	public ResultsFuture<?> rollback() throws XATransactionException {
-		final String threadId = DQPWorkContext.getWorkContext().getSessionId();
-		Callable<Void> processor = new Callable<Void>() {
-			@Override
-			public Void call() throws Exception {
-				getTransactionService().rollback(threadId);
-				return null;
-			}
-		};
-		return addWork(processor, 0);
-	}
-
-	// global txn
-	public ResultsFuture<?> commit(final XidImpl xid, final boolean onePhase) throws XATransactionException {
-		Callable<Void> processor = new Callable<Void>() {
-			@Override
-			public Void call() throws Exception {
-				DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-				getTransactionService().commit(workContext.getSessionId(), xid, onePhase, workContext.getSession().isEmbedded());
-				return null;
-			}
-		};
-		return addWork(processor, 0);
-	}
-	// global txn
-	public ResultsFuture<?> end(XidImpl xid, int flags) throws XATransactionException {
-		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-		this.getTransactionService().end(workContext.getSessionId(), xid, flags, workContext.getSession().isEmbedded());
-		return ResultsFuture.NULL_FUTURE;
-	}
-	// global txn
-	public ResultsFuture<?> forget(XidImpl xid) throws XATransactionException {
-		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-		this.getTransactionService().forget(workContext.getSessionId(), xid, workContext.getSession().isEmbedded());
-		return ResultsFuture.NULL_FUTURE;
-	}
-		
-	// global txn
-	public ResultsFuture<Integer> prepare(final XidImpl xid) throws XATransactionException {
-		Callable<Integer> processor = new Callable<Integer>() {
-			@Override
-			public Integer call() throws Exception {
-				DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-				return getTransactionService().prepare(workContext.getSessionId(),xid, workContext.getSession().isEmbedded());
-			}
-		};
-		return addWork(processor, 10);
-	}
-
-	<T> ResultsFuture<T> addWork(Callable<T> processor, int priority) {
-		FutureWork<T> work = new FutureWork<T>(processor, priority);
-		this.addWork(work);
-		return work.getResult();
-	}
-	
-	// global txn
-	public ResultsFuture<Xid[]> recover(int flag) throws XATransactionException {
-		ResultsFuture<Xid[]> result = new ResultsFuture<Xid[]>();
-		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-		result.getResultsReceiver().receiveResults(this.getTransactionService().recover(flag, workContext.getSession().isEmbedded()));
-		return result;
-	}
-	// global txn
-	public ResultsFuture<?> rollback(final XidImpl xid) throws XATransactionException {
-		Callable<Void> processor = new Callable<Void>() {
-			@Override
-			public Void call() throws Exception {
-				DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-				getTransactionService().rollback(workContext.getSessionId(),xid, workContext.getSession().isEmbedded());
-				return null;
-			}
-		};
-		return addWork(processor, 0);
-	}
-	// global txn
-	public ResultsFuture<?> start(final XidImpl xid, final int flags, final int timeout)
-			throws XATransactionException {
-		Callable<Void> processor = new Callable<Void>() {
-			@Override
-			public Void call() throws Exception {
-				DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-				getTransactionService().start(workContext.getSessionId(), xid, flags, timeout, workContext.getSession().isEmbedded());
-				return null;
-			}
-		};
-		return addWork(processor, 100);
-	}
-
-	public MetadataResult getMetadata(long requestID)
-			throws TeiidComponentException, TeiidProcessingException {
-		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-		MetaDataProcessor processor = new MetaDataProcessor(this, this.prepPlanCache,  workContext.getVdbName(), workContext.getVdbVersion());
-		return processor.processMessage(workContext.getRequestID(requestID), workContext, null, true);
-	}
-
-	public MetadataResult getMetadata(long requestID, String preparedSql,
-			boolean allowDoubleQuotedVariable)
-			throws TeiidComponentException, TeiidProcessingException {
-		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-		MetaDataProcessor processor = new MetaDataProcessor(this, this.prepPlanCache, workContext.getVdbName(), workContext.getVdbVersion());
-		return processor.processMessage(workContext.getRequestID(requestID), workContext, preparedSql, allowDoubleQuotedVariable);
-	}
-	
-	public boolean isExceptionOnMaxSourceRows() {
-		return exceptionOnMaxSourceRows;
-	}
-	
-	public int getMaxSourceRows() {
-		return maxSourceRows;
-	}
-	
-	public void setCacheFactory(CacheFactory factory) {
-		this.cacheFactory = factory;
-	}
-	
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,867 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.dqp.internal.process;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+
+import javax.resource.spi.work.Work;
+import javax.resource.spi.work.WorkEvent;
+import javax.resource.spi.work.WorkListener;
+import javax.transaction.xa.Xid;
+
+import org.teiid.adminapi.Admin;
+import org.teiid.adminapi.AdminException;
+import org.teiid.adminapi.Request.ProcessingState;
+import org.teiid.adminapi.Request.ThreadState;
+import org.teiid.adminapi.impl.CacheStatisticsMetadata;
+import org.teiid.adminapi.impl.RequestMetadata;
+import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
+import org.teiid.cache.Cache;
+import org.teiid.cache.CacheConfiguration;
+import org.teiid.cache.CacheFactory;
+import org.teiid.cache.CacheConfiguration.Policy;
+import org.teiid.client.DQP;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.client.lob.LobChunk;
+import org.teiid.client.metadata.MetadataResult;
+import org.teiid.client.util.ResultsFuture;
+import org.teiid.client.util.ResultsReceiver;
+import org.teiid.client.xa.XATransactionException;
+import org.teiid.client.xa.XidImpl;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.Streamable;
+import org.teiid.dqp.internal.process.ThreadReuseExecutor.PrioritizedRunnable;
+import org.teiid.dqp.message.AtomicRequestMessage;
+import org.teiid.dqp.message.RequestID;
+import org.teiid.dqp.service.BufferService;
+import org.teiid.dqp.service.TransactionContext;
+import org.teiid.dqp.service.TransactionService;
+import org.teiid.dqp.service.TransactionContext.Scope;
+import org.teiid.logging.CommandLogMessage;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.logging.CommandLogMessage.Event;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.tempdata.TempTableDataManager;
+import org.teiid.query.tempdata.TempTableStore;
+
+
+/**
+ * Implements the core DQP processing.
+ */
+public class DQPCore implements DQP {
+	
+	//TODO: replace with FutureTask
+	public final static class FutureWork<T> implements Work, WorkListener, PrioritizedRunnable {
+		private final Callable<T> toCall;
+		private ResultsFuture<T> result = new ResultsFuture<T>();
+		private ResultsReceiver<T> receiver = result.getResultsReceiver();
+		private int priority;
+		private long creationTime = System.currentTimeMillis();
+		private DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+
+		public FutureWork(Callable<T> processor, int priority) {
+			this.toCall = processor;
+			this.priority = priority;
+		}
+		
+		public ResultsFuture<T> getResult() {
+			return result;
+		}
+		
+		@Override
+		public void run() {
+			try {
+				receiver.receiveResults(toCall.call());
+			} catch (Throwable t) {
+				receiver.exceptionOccurred(t);
+			}
+		}
+
+		@Override
+		public void release() {
+			
+		}
+		
+		@Override
+		public void workAccepted(WorkEvent arg0) {
+			
+		}
+		
+		@Override
+		public void workCompleted(WorkEvent arg0) {
+			
+		}
+		
+		@Override
+		public void workRejected(WorkEvent arg0) {
+			receiver.exceptionOccurred(arg0.getException());
+		}
+		
+		@Override
+		public void workStarted(WorkEvent arg0) {
+			
+		}
+
+		@Override
+		public int getPriority() {
+			return priority;
+		}
+		
+		@Override
+		public long getCreationTime() {
+			return creationTime;
+		}
+		
+		@Override
+		public DQPWorkContext getDqpWorkContext() {
+			return workContext;
+		}
+	}	
+	
+	static class ClientState {
+		List<RequestID> requests;
+		TempTableStore sessionTables;
+		
+		public ClientState(TempTableStore tableStoreImpl) {
+			this.sessionTables = tableStoreImpl;
+		}
+		
+		public synchronized void addRequest(RequestID requestID) {
+			if (requests == null) {
+				requests = new LinkedList<RequestID>();
+			}
+			requests.add(requestID);
+		}
+		
+		public synchronized List<RequestID> getRequests() {
+			if (requests == null) {
+				return Collections.emptyList();
+			}
+			return new ArrayList<RequestID>(requests);
+		}
+
+		public synchronized void removeRequest(RequestID requestID) {
+			if (requests != null) {
+				requests.remove(requestID);
+			}
+		}
+		
+	}
+	
+	private ThreadReuseExecutor processWorkerPool;
+    
+    private int maxFetchSize = DQPConfiguration.DEFAULT_FETCH_SIZE;
+    private int queryThreshold = DQPConfiguration.DEFAULT_QUERY_THRESHOLD;
+    
+    // Resources
+    private BufferManager bufferManager;
+    private ProcessorDataManager dataTierMgr;
+    private SessionAwareCache<PreparedPlan> prepPlanCache;
+    private SessionAwareCache<CachedResults> rsCache;
+    private TransactionService transactionService;
+    private BufferService bufferService;
+    
+    // Query worker pool for processing plans
+    private int processorTimeslice = DQPConfiguration.DEFAULT_PROCESSOR_TIMESLICE;
+    
+    private int maxSourceRows = DQPConfiguration.DEFAULT_MAX_SOURCE_ROWS;
+    private boolean exceptionOnMaxSourceRows = true;
+    
+    private int chunkSize = Streamable.STREAMING_BATCH_SIZE_IN_BYTES;
+    
+	private Map<RequestID, RequestWorkItem> requests = new ConcurrentHashMap<RequestID, RequestWorkItem>();			
+	private Map<String, ClientState> clientState = new ConcurrentHashMap<String, ClientState>();
+    private boolean useEntitlements = false;
+    
+    private int maxActivePlans = DQPConfiguration.DEFAULT_MAX_ACTIVE_PLANS;
+    private int currentlyActivePlans;
+    private LinkedList<RequestWorkItem> waitingPlans = new LinkedList<RequestWorkItem>();
+    private CacheFactory cacheFactory;
+
+	private SessionAwareCache<CachedResults> matTables;
+    
+    /**
+     * perform a full shutdown and wait for 10 seconds for all threads to finish
+     */
+    public void stop() {
+    	processWorkerPool.shutdownNow();
+    	try {
+			processWorkerPool.awaitTermination(10, TimeUnit.SECONDS);
+		} catch (InterruptedException e) {
+		}
+    	// TODO: Should we be doing more cleanup here??
+		LogManager.logDetail(LogConstants.CTX_DQP, "Stopping the DQP"); //$NON-NLS-1$
+    }
+    
+    /**
+     * Return a list of {@link RequestMetadata} for the given session
+     */
+    public List<RequestMetadata> getRequestsForSession(String sessionId) {
+    	ClientState state = getClientState(sessionId, false);
+    	if (state == null) {
+    		return Collections.emptyList();
+    	}
+        return buildRequestInfos(state.getRequests(), -1);
+    }
+    
+    public ClientState getClientState(String key, boolean create) {
+    	if (key == null) {
+    		return null;
+    	}
+		ClientState state = clientState.get(key);
+		if (state == null && create) {
+			state = new ClientState(new TempTableStore(key));
+    		clientState.put(key, state);
+		}
+		return state;
+    }
+
+    /**
+     * Return a list of all {@link RequestMetadata} 
+     */
+    public List<RequestMetadata> getRequests() {
+		return buildRequestInfos(requests.keySet(), -1);
+    } 
+    
+    public List<RequestMetadata> getLongRunningRequests(){
+    	return buildRequestInfos(requests.keySet(), this.queryThreshold);
+    }
+
+    private List<RequestMetadata> buildRequestInfos(Collection<RequestID> ids, int longRunningQueryThreshold) {
+		List<RequestMetadata> results = new ArrayList<RequestMetadata>();
+    	
+		for (RequestID requestID : ids) {
+            RequestWorkItem holder = requests.get(requestID);
+            
+            if(holder != null && !holder.isCanceled()) {
+            	RequestMetadata req = new RequestMetadata();
+            	
+            	req.setExecutionId(holder.requestID.getExecutionID());
+            	req.setSessionId(holder.requestID.getConnectionID());
+            	req.setCommand(holder.requestMsg.getCommandString());
+            	req.setStartTime(holder.getProcessingTimestamp());
+            	req.setState(holder.isCanceled()?ProcessingState.CANCELED:holder.isDoneProcessing()?ProcessingState.DONE:ProcessingState.PROCESSING);
+            	switch (holder.getThreadState()) {
+            	case DONE:
+            	case IDLE:
+            		req.setThreadState(ThreadState.IDLE);
+            		break;
+            	default:
+            		if (holder.isProcessing()) {
+            			req.setThreadState(ThreadState.RUNNING);
+            		} else {
+            			req.setThreadState(ThreadState.QUEUED);
+            		}
+            	}
+            	if (holder.getTransactionContext() != null && holder.getTransactionContext().getTransactionType() != Scope.NONE) {
+            		req.setTransactionId(holder.getTransactionContext().getTransactionId());
+            	}
+
+                for (DataTierTupleSource conInfo : holder.getConnectorRequests()) {
+                    String connectorName = conInfo.getConnectorName();
+
+                    if (connectorName == null) {
+                    	continue;
+                    }
+                    // If the request has not yet completed processing, then
+                    // add all the subrequest messages
+                	AtomicRequestMessage arm = conInfo.getAtomicRequestMessage();
+                	RequestMetadata info = new RequestMetadata();
+                	if (conInfo.isQueued()) {
+                		info.setThreadState(ThreadState.QUEUED);
+                	} else if (conInfo.isRunning()) {
+                		info.setThreadState(ThreadState.RUNNING);
+                	} else {
+                		info.setThreadState(ThreadState.IDLE);
+                	}
+                	info.setExecutionId(arm.getRequestID().getExecutionID());
+                	info.setSessionId(holder.requestID.getConnectionID());
+                	info.setCommand(arm.getCommand().toString());
+                	info.setStartTime(arm.getProcessingTimestamp());
+                	info.setSourceRequest(true);
+                	info.setNodeId(arm.getAtomicRequestID().getNodeID());
+                	info.setState(conInfo.isCanceled()?ProcessingState.CANCELED:conInfo.isDone()?ProcessingState.DONE:ProcessingState.PROCESSING);
+        			results.add(info);
+                }
+                
+                // check if only need long running queries.
+                long elapsedTime = System.currentTimeMillis() - req.getStartTime();
+                if (longRunningQueryThreshold == -1 || elapsedTime > longRunningQueryThreshold) {
+                	results.add(req);
+                }
+            }
+        }
+    	return results;
+	}    
+
+	public ResultsFuture<ResultsMessage> executeRequest(long reqID,RequestMessage requestMsg) {
+    	DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+		RequestID requestID = workContext.getRequestID(reqID);
+		requestMsg.setFetchSize(Math.min(requestMsg.getFetchSize(), maxFetchSize));
+		Request request = null;
+	    if ( requestMsg.isPreparedStatement() || requestMsg.isCallableStatement()) {
+	    	request = new PreparedStatementRequest(prepPlanCache);
+	    } else {
+	    	request = new Request();
+	    }
+	    ClientState state = this.getClientState(workContext.getSessionId(), true);
+	    request.initialize(requestMsg, bufferManager,
+				dataTierMgr, transactionService, state.sessionTables,
+				workContext, this.useEntitlements, this.prepPlanCache);
+		request.setResultSetCacheEnabled(this.rsCache != null);
+        ResultsFuture<ResultsMessage> resultsFuture = new ResultsFuture<ResultsMessage>();
+        RequestWorkItem workItem = new RequestWorkItem(this, requestMsg, request, resultsFuture.getResultsReceiver(), requestID, workContext);
+    	logMMCommand(workItem, Event.NEW, null); 
+        addRequest(requestID, workItem, state);
+        synchronized (waitingPlans) {
+			if (currentlyActivePlans < maxActivePlans) {
+				startActivePlan(workItem);
+			} else {
+				if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+		            LogManager.logDetail(LogConstants.CTX_DQP, "Queuing plan, since max plans has been reached.");  //$NON-NLS-1$
+		        }  
+				waitingPlans.add(workItem);
+			}
+		}
+        return resultsFuture;
+    }
+	
+	public ResultsFuture<ResultsMessage> processCursorRequest(long reqID,
+			int batchFirst, int fetchSize) throws TeiidProcessingException {
+        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+            LogManager.logDetail(LogConstants.CTX_DQP, "DQP process cursor request from " + batchFirst);  //$NON-NLS-1$
+        }
+		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+        ResultsFuture<ResultsMessage> resultsFuture = new ResultsFuture<ResultsMessage>();
+		RequestWorkItem workItem = getRequestWorkItem(workContext.getRequestID(reqID));
+		workItem.requestMore(batchFirst, batchFirst + Math.min(fetchSize, maxFetchSize) - 1, resultsFuture.getResultsReceiver());
+		return resultsFuture;
+	}
+
+	void addRequest(RequestID requestID, RequestWorkItem workItem, ClientState state) {
+		this.requests.put(requestID, workItem);
+		state.addRequest(requestID);
+	}
+
+	private void startActivePlan(RequestWorkItem workItem) {
+		workItem.active = true;
+		this.addWork(workItem);
+		this.currentlyActivePlans++;
+	}
+	
+    void finishProcessing(final RequestWorkItem workItem) {
+    	synchronized (waitingPlans) {
+    		if (!workItem.active) {
+        		return;
+        	}
+        	workItem.active = false;
+    		currentlyActivePlans--;
+			if (!waitingPlans.isEmpty()) {
+				startActivePlan(waitingPlans.remove());
+			}
+		}
+    }
+    
+    void removeRequest(final RequestWorkItem workItem) {
+    	finishProcessing(workItem);
+    	this.requests.remove(workItem.requestID);
+    	ClientState state = getClientState(workItem.getDqpWorkContext().getSessionId(), false);
+    	if (state != null) {
+    		state.removeRequest(workItem.requestID);
+    	}
+    }
+    
+    void addWork(Runnable work) {
+		this.processWorkerPool.execute(work);
+    }
+    
+    void scheduleWork(final Runnable r, int priority, long delay) {
+		this.processWorkerPool.schedule(new FutureWork<Void>(new Callable<Void>() {
+			@Override
+			public Void call() throws Exception {
+				r.run();
+				return null;
+			}
+		}, priority), delay, TimeUnit.MILLISECONDS);
+    }
+    
+	public ResultsFuture<?> closeLobChunkStream(int lobRequestId,
+			long requestId, String streamId)
+			throws TeiidProcessingException {
+        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+            LogManager.logDetail(LogConstants.CTX_DQP, "Request to close the Lob stream with Stream id="+streamId+" instance id="+lobRequestId);  //$NON-NLS-1$//$NON-NLS-2$
+        }   
+        DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+        RequestWorkItem workItem = safeGetWorkItem(workContext.getRequestID(requestId));
+        if (workItem != null) {
+	        workItem.removeLobStream(lobRequestId);
+        }
+        return ResultsFuture.NULL_FUTURE;
+    }
+	    
+	public ResultsFuture<LobChunk> requestNextLobChunk(int lobRequestId,
+			long requestId, String streamId)
+			throws TeiidProcessingException {
+        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+            LogManager.logDetail(LogConstants.CTX_DQP, "Request for next Lob chunk with Stream id="+streamId+" instance id="+lobRequestId);  //$NON-NLS-1$//$NON-NLS-2$
+        }  
+        RequestWorkItem workItem = getRequestWorkItem(DQPWorkContext.getWorkContext().getRequestID(requestId));
+        ResultsFuture<LobChunk> resultsFuture = new ResultsFuture<LobChunk>();
+        workItem.processLobChunkRequest(streamId, lobRequestId, resultsFuture.getResultsReceiver());
+        return resultsFuture;
+    }
+    
+//    /**
+//     * Cancels a node in the request. (This request is called by the 
+//     * client directly using the admin API), so if this does not support
+//     * partial results then remove the original request.
+//     * @throws MetaMatrixComponentException 
+//     */
+//    public void cancelAtomicRequest(AtomicRequestID requestID) throws MetaMatrixComponentException {                    
+//        RequestWorkItem workItem = safeGetWorkItem(requestID.getRequestID());
+//        if (workItem == null) {
+//    		LogManager.logDetail(LogConstants.CTX_DQP, "Could not cancel", requestID, "parent request does not exist"); //$NON-NLS-1$ //$NON-NLS-2$
+//        	return;
+//        }
+//        workItem.requestAtomicRequestCancel(requestID);
+//    }
+    
+    RequestWorkItem getRequestWorkItem(RequestID reqID) throws TeiidProcessingException {
+    	RequestWorkItem result = this.requests.get(reqID);
+    	if (result == null) {
+    		throw new TeiidProcessingException(QueryPlugin.Util.getString("DQPCore.The_request_has_been_closed.", reqID));//$NON-NLS-1$
+    	}
+    	return result;
+    }
+    
+	RequestWorkItem safeGetWorkItem(Object processorID) {
+    	return this.requests.get(processorID);
+	}
+	
+    public WorkerPoolStatisticsMetadata getWorkerPoolStatistics() {
+    	return this.processWorkerPool.getStats();
+    }
+           
+    public void terminateSession(String sessionId) {
+        // sometimes there will not be any atomic requests pending, in that
+        // situation we still need to clear the master request from our map
+        ClientState state = getClientState(sessionId, false);
+        if (state != null) {
+	        for (RequestID reqId : state.getRequests()) {
+	            try {
+	                cancelRequest(reqId);
+	            } catch (TeiidComponentException err) {
+	                LogManager.logWarning(LogConstants.CTX_DQP, err, "Failed to cancel " + reqId); //$NON-NLS-1$
+				}
+	        }
+        }
+        
+        try {
+            transactionService.cancelTransactions(sessionId, false);
+        } catch (XATransactionException err) {
+            LogManager.logWarning(LogConstants.CTX_DQP, "rollback failed for requestID=" + sessionId); //$NON-NLS-1$
+        } 
+    }
+
+    public boolean cancelRequest(String sessionId, long executionId) throws TeiidComponentException {
+    	RequestID requestID = new RequestID(sessionId, executionId);
+    	return cancelRequest(requestID);
+    }
+    
+    private boolean cancelRequest(RequestID requestID) throws TeiidComponentException {
+        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+            LogManager.logDetail(LogConstants.CTX_DQP, "cancelQuery for requestID=" + requestID); //$NON-NLS-1$
+        }
+        
+        boolean markCancelled = false;
+        
+        RequestWorkItem workItem = safeGetWorkItem(requestID);
+        if (workItem != null) {
+        	markCancelled = workItem.requestCancel();
+        }
+    	if (markCancelled) {
+            logMMCommand(workItem, Event.CANCEL, null);
+    	} else {
+    		LogManager.logDetail(LogConstants.CTX_DQP, QueryPlugin.Util.getString("DQPCore.failed_to_cancel")); //$NON-NLS-1$
+    	}
+        return markCancelled;
+    }
+    
+	public ResultsFuture<?> closeRequest(long requestId) throws TeiidProcessingException, TeiidComponentException {
+        DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+        closeRequest(workContext.getRequestID(requestId));
+        return ResultsFuture.NULL_FUTURE;
+	}
+    
+    /**
+     * Close the request with given ID 
+     * @param requestID
+     * @throws TeiidComponentException 
+     */
+    void closeRequest(RequestID requestID) throws TeiidComponentException {
+        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+            LogManager.logDetail(LogConstants.CTX_DQP, "closeQuery for requestID=" + requestID); //$NON-NLS-1$
+        }
+        
+        RequestWorkItem workItem = safeGetWorkItem(requestID);
+        if (workItem != null) {
+        	workItem.requestClose();
+        } else {
+        	LogManager.logDetail(LogConstants.CTX_DQP, requestID + " close call ignored as the request has already been removed."); //$NON-NLS-1$
+        }
+    }
+    
+    private void clearPlanCache(){
+        LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("DQPCore.Clearing_prepared_plan_cache")); //$NON-NLS-1$
+        this.prepPlanCache.clearAll();
+    }
+
+	private void clearResultSetCache() {
+		//clear cache in server
+		if(rsCache != null){
+			rsCache.clearAll();
+		}
+	}
+	
+    private void clearPlanCache(String vdbName, int version){
+        LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("DQPCore.Clearing_prepared_plan_cache")); //$NON-NLS-1$
+        this.prepPlanCache.clearForVDB(vdbName, version);
+    }
+
+	private void clearResultSetCache(String vdbName, int version) {
+		//clear cache in server
+		if(rsCache != null){
+			rsCache.clearForVDB(vdbName, version);
+		}
+	}
+	
+	public CacheStatisticsMetadata getCacheStatistics(String cacheType) {
+		if (cacheType.equalsIgnoreCase(Admin.Cache.PREPARED_PLAN_CACHE.toString())) {
+			return buildCacheStats(Admin.Cache.PREPARED_PLAN_CACHE.toString(), this.prepPlanCache);
+		}
+		else if (cacheType.equalsIgnoreCase(Admin.Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString())) {
+			return buildCacheStats(Admin.Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString(), this.rsCache);
+		}
+		return null;
+	}
+	
+	private CacheStatisticsMetadata buildCacheStats(String name, SessionAwareCache cache) {
+		CacheStatisticsMetadata stats = new CacheStatisticsMetadata();
+		stats.setName(name);
+		stats.setHitRatio(cache.getRequestCount() == 0?0:((double)cache.getCacheHitCount()/cache.getRequestCount())*100);
+		stats.setTotalEntries(cache.getTotalCacheEntries());
+		stats.setRequestCount(cache.getRequestCount());
+		return stats;
+	}
+	
+    public Collection<String> getCacheTypes(){
+    	ArrayList<String> caches = new ArrayList<String>();
+    	caches.add(Admin.Cache.PREPARED_PLAN_CACHE.toString());
+    	caches.add(Admin.Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString());
+    	return caches;
+    }	
+	
+	public void clearCache(String cacheType) {
+		Admin.Cache cache = Admin.Cache.valueOf(cacheType);
+		switch (cache) {
+		case PREPARED_PLAN_CACHE:
+			clearPlanCache();
+			break;
+		case QUERY_SERVICE_RESULT_SET_CACHE:
+			clearResultSetCache();
+			break;
+		}
+	}
+	
+	public void clearCache(String cacheType, String vdbName, int version) {
+		Admin.Cache cache = Admin.Cache.valueOf(cacheType);
+		switch (cache) {
+		case PREPARED_PLAN_CACHE:
+			clearPlanCache(vdbName, version);
+			break;
+		case QUERY_SERVICE_RESULT_SET_CACHE:
+			clearResultSetCache(vdbName, version);
+			break;
+		}
+		if (this.matTables != null) {
+			this.matTables.clearForVDB(vdbName, version);
+		}
+	}	
+    
+	public Collection<org.teiid.adminapi.Transaction> getTransactions() {
+		return this.transactionService.getTransactions();
+	}
+	
+	public void terminateTransaction(String xid) throws AdminException {
+		this.transactionService.terminateTransaction(xid);
+	}	
+	
+    void logMMCommand(RequestWorkItem workItem, Event status, Integer rowCount) {
+    	if (!LogManager.isMessageToBeRecorded(LogConstants.CTX_COMMANDLOGGING, MessageLevel.DETAIL)) {
+    		return;
+    	}
+    	
+        RequestMessage msg = workItem.requestMsg;
+        DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+        RequestID rID = new RequestID(workContext.getSessionId(), msg.getExecutionId());
+    	String txnID = null;
+		TransactionContext tc = workItem.getTransactionContext();
+		if (tc != null && tc.getTransactionType() != Scope.NONE) {
+			txnID = tc.getTransactionId();
+		}
+    	String appName = workContext.getAppName();
+        // Log to request log
+        CommandLogMessage message = null;
+        if (status == Event.NEW) {
+            message = new CommandLogMessage(System.currentTimeMillis(), rID.toString(), txnID, workContext.getSessionId(), appName, workContext.getUserName(), workContext.getVdbName(), workContext.getVdbVersion(), msg.getCommandString());
+        } else {
+            message = new CommandLogMessage(System.currentTimeMillis(), rID.toString(), txnID, workContext.getSessionId(), workContext.getUserName(), workContext.getVdbName(), workContext.getVdbVersion(), rowCount, status);
+        }
+        LogManager.log(MessageLevel.DETAIL, LogConstants.CTX_COMMANDLOGGING, message);
+    }
+    
+    ProcessorDataManager getDataTierManager() {
+    	return this.dataTierMgr;
+    }
+    
+	public BufferManager getBufferManager() {
+		return bufferManager;
+	}
+
+	public TransactionService getTransactionService() {
+		return transactionService;
+	}
+
+	SessionAwareCache<CachedResults> getRsCache() {
+		return rsCache;
+	}
+	
+	int getProcessorTimeSlice() {
+		return this.processorTimeslice;
+	}	
+	
+	int getChunkSize() {
+		return chunkSize;
+	}
+	
+	public void start(DQPConfiguration config) {
+		this.processorTimeslice = config.getTimeSliceInMilli();
+        this.maxFetchSize = config.getMaxRowsFetchSize();
+        this.useEntitlements = config.getUseDataRoles();
+        this.queryThreshold = config.getQueryThresholdInSecs();
+        this.maxSourceRows = config.getMaxSourceRows();
+        this.exceptionOnMaxSourceRows = config.isExceptionOnMaxSourceRows();
+        
+        this.chunkSize = config.getLobChunkSizeInKB() * 1024;
+
+        //get buffer manager
+        this.bufferManager = bufferService.getBufferManager();
+        
+        //result set cache
+        CacheConfiguration rsCacheConfig = config.getResultsetCacheConfig();
+        if (rsCacheConfig != null && rsCacheConfig.isEnabled()) {
+			this.rsCache = new SessionAwareCache<CachedResults>(this.cacheFactory, Cache.Type.RESULTSET, rsCacheConfig);
+			this.rsCache.setBufferManager(this.bufferManager);
+        }
+
+        //prepared plan cache
+        prepPlanCache = new SessionAwareCache<PreparedPlan>(this.cacheFactory, Cache.Type.PREPAREDPLAN,  new CacheConfiguration(Policy.LRU, 60*60*8, config.getPreparedPlanCacheMaxCount()));
+        prepPlanCache.setBufferManager(this.bufferManager);
+		
+        
+        this.processWorkerPool = new ThreadReuseExecutor(DQPConfiguration.PROCESS_PLAN_QUEUE_NAME, config.getMaxThreads());
+        
+        if (cacheFactory.isReplicated()) {
+        	matTables = new SessionAwareCache<CachedResults>();
+        }
+        
+        dataTierMgr = new TempTableDataManager(new DataTierManagerImpl(this,
+                                            this.bufferService), this.bufferManager, this.processWorkerPool, this.rsCache, matTables, this.cacheFactory); 
+	}
+	
+	public void setBufferService(BufferService service) {
+		this.bufferService = service;
+	}
+	
+	public void setTransactionService(TransactionService service) {
+		this.transactionService = service;
+	}
+	
+	@Override
+	public boolean cancelRequest(long requestID)
+			throws TeiidProcessingException, TeiidComponentException {
+		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+		return this.cancelRequest(workContext.getRequestID(requestID));
+	}
+	
+	// local txn
+	public ResultsFuture<?> begin() throws XATransactionException {
+    	String threadId = DQPWorkContext.getWorkContext().getSessionId();
+    	this.getTransactionService().begin(threadId);
+    	return ResultsFuture.NULL_FUTURE;
+	}
+	
+	// local txn
+	public ResultsFuture<?> commit() throws XATransactionException {
+		final String threadId = DQPWorkContext.getWorkContext().getSessionId();
+		Callable<Void> processor = new Callable<Void>() {
+			@Override
+			public Void call() throws Exception {
+				getTransactionService().commit(threadId);
+				return null;
+			}
+		};
+		return addWork(processor, 0);
+	}
+	
+	// local txn
+	public ResultsFuture<?> rollback() throws XATransactionException {
+		final String threadId = DQPWorkContext.getWorkContext().getSessionId();
+		Callable<Void> processor = new Callable<Void>() {
+			@Override
+			public Void call() throws Exception {
+				getTransactionService().rollback(threadId);
+				return null;
+			}
+		};
+		return addWork(processor, 0);
+	}
+
+	// global txn
+	public ResultsFuture<?> commit(final XidImpl xid, final boolean onePhase) throws XATransactionException {
+		Callable<Void> processor = new Callable<Void>() {
+			@Override
+			public Void call() throws Exception {
+				DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+				getTransactionService().commit(workContext.getSessionId(), xid, onePhase, workContext.getSession().isEmbedded());
+				return null;
+			}
+		};
+		return addWork(processor, 0);
+	}
+	// global txn
+	public ResultsFuture<?> end(XidImpl xid, int flags) throws XATransactionException {
+		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+		this.getTransactionService().end(workContext.getSessionId(), xid, flags, workContext.getSession().isEmbedded());
+		return ResultsFuture.NULL_FUTURE;
+	}
+	// global txn
+	public ResultsFuture<?> forget(XidImpl xid) throws XATransactionException {
+		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+		this.getTransactionService().forget(workContext.getSessionId(), xid, workContext.getSession().isEmbedded());
+		return ResultsFuture.NULL_FUTURE;
+	}
+		
+	// global txn
+	public ResultsFuture<Integer> prepare(final XidImpl xid) throws XATransactionException {
+		Callable<Integer> processor = new Callable<Integer>() {
+			@Override
+			public Integer call() throws Exception {
+				DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+				return getTransactionService().prepare(workContext.getSessionId(),xid, workContext.getSession().isEmbedded());
+			}
+		};
+		return addWork(processor, 10);
+	}
+
+	<T> ResultsFuture<T> addWork(Callable<T> processor, int priority) {
+		FutureWork<T> work = new FutureWork<T>(processor, priority);
+		this.addWork(work);
+		return work.getResult();
+	}
+	
+	// global txn
+	public ResultsFuture<Xid[]> recover(int flag) throws XATransactionException {
+		ResultsFuture<Xid[]> result = new ResultsFuture<Xid[]>();
+		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+		result.getResultsReceiver().receiveResults(this.getTransactionService().recover(flag, workContext.getSession().isEmbedded()));
+		return result;
+	}
+	// global txn
+	public ResultsFuture<?> rollback(final XidImpl xid) throws XATransactionException {
+		Callable<Void> processor = new Callable<Void>() {
+			@Override
+			public Void call() throws Exception {
+				DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+				getTransactionService().rollback(workContext.getSessionId(),xid, workContext.getSession().isEmbedded());
+				return null;
+			}
+		};
+		return addWork(processor, 0);
+	}
+	// global txn
+	public ResultsFuture<?> start(final XidImpl xid, final int flags, final int timeout)
+			throws XATransactionException {
+		Callable<Void> processor = new Callable<Void>() {
+			@Override
+			public Void call() throws Exception {
+				DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+				getTransactionService().start(workContext.getSessionId(), xid, flags, timeout, workContext.getSession().isEmbedded());
+				return null;
+			}
+		};
+		return addWork(processor, 100);
+	}
+
+	public MetadataResult getMetadata(long requestID)
+			throws TeiidComponentException, TeiidProcessingException {
+		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+		MetaDataProcessor processor = new MetaDataProcessor(this, this.prepPlanCache,  workContext.getVdbName(), workContext.getVdbVersion());
+		return processor.processMessage(workContext.getRequestID(requestID), workContext, null, true);
+	}
+
+	public MetadataResult getMetadata(long requestID, String preparedSql,
+			boolean allowDoubleQuotedVariable)
+			throws TeiidComponentException, TeiidProcessingException {
+		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+		MetaDataProcessor processor = new MetaDataProcessor(this, this.prepPlanCache, workContext.getVdbName(), workContext.getVdbVersion());
+		return processor.processMessage(workContext.getRequestID(requestID), workContext, preparedSql, allowDoubleQuotedVariable);
+	}
+	
+	public boolean isExceptionOnMaxSourceRows() {
+		return exceptionOnMaxSourceRows;
+	}
+	
+	public int getMaxSourceRows() {
+		return maxSourceRows;
+	}
+	
+	public void setCacheFactory(CacheFactory factory) {
+		this.cacheFactory = factory;
+	}
+	
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,249 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.dqp.internal.process;
-
-import java.io.Serializable;
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.FutureTask;
-
-import javax.security.auth.Subject;
-
-import org.teiid.adminapi.DataPolicy;
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.client.security.SessionToken;
-import org.teiid.dqp.message.RequestID;
-import org.teiid.security.SecurityHelper;
-
-
-public class DQPWorkContext implements Serializable {
-	
-	private static final long serialVersionUID = -6389893410233192977L;
-	
-	private static ThreadLocal<DQPWorkContext> CONTEXTS = new ThreadLocal<DQPWorkContext>() {
-		protected DQPWorkContext initialValue() {
-			return new DQPWorkContext();
-		}
-	};
-
-	public static DQPWorkContext getWorkContext() {
-		return CONTEXTS.get();
-	}
-	
-	public static void setWorkContext(DQPWorkContext context) {
-		CONTEXTS.set(context);
-	}
-
-	public static void releaseWorkContext() {
-		CONTEXTS.set(null);
-	}	
-	
-	private SessionMetadata session = new SessionMetadata();
-    private String clientAddress;
-    private String clientHostname;
-    private SecurityHelper securityHelper;
-    private HashMap<String, DataPolicy> policies;
-    
-    public DQPWorkContext() {
-	}
-    
-    public SessionMetadata getSession() {
-		return session;
-	}
-    
-    public void setSession(SessionMetadata session) {
-		this.session = session;
-		this.policies = null;
-	}
-    
-    public void setSecurityHelper(SecurityHelper securityHelper) {
-		this.securityHelper = securityHelper;
-	}
-
-    /**
-     * @return
-     */
-    public String getUserName() {
-		return session.getUserName();
-    }
-    
-    public Subject getSubject() {
-    	if (session.getLoginContext() != null) {
-    		return session.getLoginContext().getSubject();
-    	}
-    	return null;
-    }
-    
-    /**
-     * @return
-     */
-    public String getVdbName() {
-        return session.getVDBName();
-    }
-
-    /**
-     * @return
-     */
-    public int getVdbVersion() {
-        return session.getVDBVersion();
-    }
-
-	public String getSessionId() {
-		return this.session.getSessionId();
-	}
-
-	public String getAppName() {
-		return session.getApplicationName();
-	}
-	
-	public RequestID getRequestID(long exeuctionId) {
-		return new RequestID(this.getSessionId(), exeuctionId);
-	}
-	
-	public SessionToken getSessionToken() {
-		return session.getSessionToken();
-	}
-
-	public void setClientAddress(String clientAddress) {
-		this.clientAddress = clientAddress;
-	}
-
-	/**
-	 * Get the client address from the socket transport - not as reported from the client
-	 * @return
-	 */
-	public String getClientAddress() {
-		return clientAddress;
-	}
-
-	public void setClientHostname(String clientHostname) {
-		this.clientHostname = clientHostname;
-	}
-
-	/**
-	 * Get the client hostname from the socket transport - not as reported from the client
-	 * @return
-	 */
-	public String getClientHostname() {
-		return clientHostname;
-	}
-	
-	public String getSecurityDomain() {
-		return this.session.getSecurityDomain();
-	}
-
-	public Object getSecurityContext() {
-		return session.getSecurityContext();
-	}
-	
-	public VDBMetaData getVDB() {
-		return session.getVdb();
-	}
-	
-	public <V> V runInContext(Callable<V> callable) throws Throwable {
-		FutureTask<V> task = new FutureTask<V>(callable);
-		runInContext(task);
-		try {
-			return task.get();
-		} catch (ExecutionException e) {
-			throw e.getCause();
-		}
-	}
-	
-	public void runInContext(final Runnable runnable) {
-		DQPWorkContext.setWorkContext(this);
-		boolean associated = false;
-		if (securityHelper != null && this.getSubject() != null) {
-			associated = securityHelper.assosiateSecurityContext(this.getSecurityDomain(), this.getSecurityContext());			
-		}
-		try {
-			runnable.run();
-		} finally {
-			if (associated) {
-				securityHelper.clearSecurityContext(this.getSecurityDomain());			
-			}
-			DQPWorkContext.releaseWorkContext();
-		}
-	}
-
-	public HashMap<String, DataPolicy> getAllowedDataPolicies() {
-		if (this.policies == null) {
-	    	this.policies = new HashMap<String, DataPolicy>();
-	    	Set<String> userRoles = getUserRoles();
-	    	if (userRoles.isEmpty()) {
-	    		return this.policies;
-	    	}
-	    	
-	    	// get data roles from the VDB
-	    	for (DataPolicy policy : getVDB().getDataPolicies()) {
-	        	if (matchesPrincipal(userRoles, policy)) {
-	        		this.policies.put(policy.getName(), policy);
-	        	}
-	        }
-		}
-        return this.policies;
-    }
-    
-	private boolean matchesPrincipal(Set<String> userRoles, DataPolicy policy) {
-		if (policy.isAnyAuthenticated()) {
-			return true;
-		}
-		List<String> roles = policy.getMappedRoleNames();
-		for (String role:roles) {
-			if (userRoles.contains(role)) {
-				return true;
-			}
-		}
-		return false;
-	}    
-
-	private Set<String> getUserRoles() {
-		Set<String> roles = new HashSet<String>();
-		
-		if (getSubject() == null) {
-			return Collections.emptySet();
-		}
-		
-		Set<Principal> principals = getSubject().getPrincipals();
-		for(Principal p: principals) {
-			// this JBoss specific, but no code level dependencies
-			if ((p instanceof Group) && p.getName().equals("Roles")){ //$NON-NLS-1$
-				Group g = (Group)p;
-				Enumeration<? extends Principal> rolesPrinciples = g.members();
-				while(rolesPrinciples.hasMoreElements()) {
-					roles.add(rolesPrinciples.nextElement().getName());	
-				}
-			}
-		}
-		return roles;
-	}	
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,239 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.dqp.internal.process;
+
+import java.io.Serializable;
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+
+import javax.security.auth.Subject;
+
+import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.client.security.SessionToken;
+import org.teiid.dqp.message.RequestID;
+import org.teiid.security.SecurityHelper;
+
+
+public class DQPWorkContext implements Serializable {
+	
+	private static final long serialVersionUID = -6389893410233192977L;
+	
+	private static ThreadLocal<DQPWorkContext> CONTEXTS = new ThreadLocal<DQPWorkContext>() {
+		protected DQPWorkContext initialValue() {
+			return new DQPWorkContext();
+		}
+	};
+
+	public static DQPWorkContext getWorkContext() {
+		return CONTEXTS.get();
+	}
+	
+	public static void setWorkContext(DQPWorkContext context) {
+		CONTEXTS.set(context);
+	}
+
+	public static void releaseWorkContext() {
+		CONTEXTS.set(null);
+	}	
+	
+	private SessionMetadata session = new SessionMetadata();
+    private String clientAddress;
+    private String clientHostname;
+    private SecurityHelper securityHelper;
+    private HashMap<String, DataPolicy> policies;
+    
+    public DQPWorkContext() {
+	}
+    
+    public SessionMetadata getSession() {
+		return session;
+	}
+    
+    public void setSession(SessionMetadata session) {
+		this.session = session;
+		this.policies = null;
+	}
+    
+    public void setSecurityHelper(SecurityHelper securityHelper) {
+		this.securityHelper = securityHelper;
+	}
+
+    /**
+     * @return
+     */
+    public String getUserName() {
+		return session.getUserName();
+    }
+    
+    public Subject getSubject() {
+    	if (session.getLoginContext() != null) {
+    		return session.getLoginContext().getSubject();
+    	}
+    	return null;
+    }
+    
+    /**
+     * @return
+     */
+    public String getVdbName() {
+        return session.getVDBName();
+    }
+
+    /**
+     * @return
+     */
+    public int getVdbVersion() {
+        return session.getVDBVersion();
+    }
+
+	public String getSessionId() {
+		return this.session.getSessionId();
+	}
+
+	public String getAppName() {
+		return session.getApplicationName();
+	}
+	
+	public RequestID getRequestID(long exeuctionId) {
+		return new RequestID(this.getSessionId(), exeuctionId);
+	}
+	
+	public SessionToken getSessionToken() {
+		return session.getSessionToken();
+	}
+
+	public void setClientAddress(String clientAddress) {
+		this.clientAddress = clientAddress;
+	}
+
+	/**
+	 * Get the client address from the socket transport - not as reported from the client
+	 * @return
+	 */
+	public String getClientAddress() {
+		return clientAddress;
+	}
+
+	public void setClientHostname(String clientHostname) {
+		this.clientHostname = clientHostname;
+	}
+
+	/**
+	 * Get the client hostname from the socket transport - not as reported from the client
+	 * @return
+	 */
+	public String getClientHostname() {
+		return clientHostname;
+	}
+	
+	public String getSecurityDomain() {
+		return this.session.getSecurityDomain();
+	}
+
+	public Object getSecurityContext() {
+		return session.getSecurityContext();
+	}
+	
+	public VDBMetaData getVDB() {
+		return session.getVdb();
+	}
+	
+	public <V> V runInContext(Callable<V> callable) throws Throwable {
+		FutureTask<V> task = new FutureTask<V>(callable);
+		runInContext(task);
+		try {
+			return task.get();
+		} catch (ExecutionException e) {
+			throw e.getCause();
+		}
+	}
+	
+	public void runInContext(final Runnable runnable) {
+		DQPWorkContext.setWorkContext(this);
+		boolean associated = false;
+		if (securityHelper != null && this.getSubject() != null) {
+			associated = securityHelper.assosiateSecurityContext(this.getSecurityDomain(), this.getSecurityContext());			
+		}
+		try {
+			runnable.run();
+		} finally {
+			if (associated) {
+				securityHelper.clearSecurityContext(this.getSecurityDomain());			
+			}
+			DQPWorkContext.releaseWorkContext();
+		}
+	}
+
+	public HashMap<String, DataPolicy> getAllowedDataPolicies() {
+		if (this.policies == null) {
+	    	this.policies = new HashMap<String, DataPolicy>();
+	    	Set<String> userRoles = getUserRoles();
+	    	
+	    	// get data roles from the VDB
+	    	for (DataPolicy policy : getVDB().getDataPolicies()) {
+	        	if (matchesPrincipal(userRoles, policy)) {
+	        		this.policies.put(policy.getName(), policy);
+	        	}
+	        }
+		}
+        return this.policies;
+    }
+    
+	private boolean matchesPrincipal(Set<String> userRoles, DataPolicy policy) {
+		if (policy.isAnyAuthenticated()) {
+			return true;
+		}
+		return !Collections.disjoint(policy.getMappedRoleNames(), userRoles);
+	}    
+
+	private Set<String> getUserRoles() {
+		Set<String> roles = new HashSet<String>();
+		
+		if (getSubject() == null) {
+			return Collections.emptySet();
+		}
+		
+		Set<Principal> principals = getSubject().getPrincipals();
+		for(Principal p: principals) {
+			// this JBoss specific, but no code level dependencies
+			if ((p instanceof Group) && p.getName().equals("Roles")){ //$NON-NLS-1$
+				Group g = (Group)p;
+				Enumeration<? extends Principal> rolesPrinciples = g.members();
+				while(rolesPrinciples.hasMoreElements()) {
+					roles.add(rolesPrinciples.nextElement().getName());	
+				}
+			}
+		}
+		return roles;
+	}	
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,723 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.dqp.internal.process;
-
-import java.sql.ResultSet;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.client.SourceWarning;
-import org.teiid.client.RequestMessage.ShowPlan;
-import org.teiid.client.lob.LobChunk;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.client.util.ResultsReceiver;
-import org.teiid.client.xa.XATransactionException;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.TupleBatch;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
-import org.teiid.dqp.internal.process.ThreadReuseExecutor.PrioritizedRunnable;
-import org.teiid.dqp.message.AtomicRequestID;
-import org.teiid.dqp.message.RequestID;
-import org.teiid.dqp.service.TransactionContext;
-import org.teiid.dqp.service.TransactionService;
-import org.teiid.dqp.service.TransactionContext.Scope;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.logging.MessageLevel;
-import org.teiid.logging.CommandLogMessage.Event;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.function.metadata.FunctionMethod;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.query.processor.BatchCollector;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-
-public class RequestWorkItem extends AbstractWorkItem implements PrioritizedRunnable {
-	
-	private enum ProcessingState {NEW, PROCESSING, CLOSE}
-	private ProcessingState state = ProcessingState.NEW;
-    
-	private enum TransactionState {NONE, ACTIVE, DONE}
-	private TransactionState transactionState = TransactionState.NONE;
-	
-	/*
-	 * Obtained at construction time 
-	 */
-	protected final DQPCore dqpCore;
-    final RequestMessage requestMsg;    
-    final RequestID requestID;
-    private Request request; //provides the processing plan, held on a temporary basis
-    private final int processorTimeslice;
-	private CacheID cid;
-	private final TransactionService transactionService;
-	private final DQPWorkContext dqpWorkContext;
-	boolean active;
-	
-    /*
-     * obtained during new
-     */
-    private volatile QueryProcessor processor;
-    private BatchCollector collector;
-    private Command originalCommand;
-    private AnalysisRecord analysisRecord;
-    private TransactionContext transactionContext;
-    TupleBuffer resultsBuffer;
-    private boolean returnsUpdateCount;
-    
-    /*
-     * maintained during processing
-     */
-    private Throwable processingException;
-    private Map<AtomicRequestID, DataTierTupleSource> connectorInfo = new ConcurrentHashMap<AtomicRequestID, DataTierTupleSource>(4);
-    // This exception contains details of all the atomic requests that failed when query is run in partial results mode.
-    private List<TeiidException> warnings = new LinkedList<TeiidException>();
-    private volatile boolean doneProducingBatches;
-    private volatile boolean isClosed;
-    private volatile boolean isCanceled;
-    private volatile boolean closeRequested;
-
-	//results request
-	private ResultsReceiver<ResultsMessage> resultsReceiver;
-	private int begin;
-	private int end;
-    private TupleBatch savedBatch;
-    private Map<Integer, LobWorkItem> lobStreams = new ConcurrentHashMap<Integer, LobWorkItem>(4);    
-    
-    /**The time when command begins processing on the server.*/
-    private long processingTimestamp = System.currentTimeMillis();
-    
-    public RequestWorkItem(DQPCore dqpCore, RequestMessage requestMsg, Request request, ResultsReceiver<ResultsMessage> receiver, RequestID requestID, DQPWorkContext workContext) {
-        this.requestMsg = requestMsg;
-        this.requestID = requestID;
-        this.processorTimeslice = dqpCore.getProcessorTimeSlice();
-        this.transactionService = dqpCore.getTransactionService();
-        this.dqpCore = dqpCore;
-        this.request = request;
-        this.dqpWorkContext = workContext;
-        this.requestResults(1, requestMsg.getFetchSize(), receiver);
-    }
-    
-    private boolean isForwardOnly() {
-    	return this.cid == null && requestMsg.getCursorType() == ResultSet.TYPE_FORWARD_ONLY;    	
-    }
-    
-	/**
-	 * Ask for results.
-	 * @param beginRow
-	 * @param endRow
-	 */
-    synchronized void requestResults(int beginRow, int endRow, ResultsReceiver<ResultsMessage> receiver) {
-		if (this.resultsReceiver != null) {
-			throw new IllegalStateException("Results already requested"); //$NON-NLS-1$\
-		}
-		this.resultsReceiver = receiver;
-		this.begin = beginRow;
-		this.end = endRow;
-	}
-    
-	@Override
-	protected boolean isDoneProcessing() {
-		return isClosed;
-	}
-
-	@Override
-	protected void resumeProcessing() {
-		if (doneProducingBatches && !closeRequested && !isCanceled) {
-			this.run(); // just run in the IO thread
-		} else {
-			dqpCore.addWork(this);
-		}
-	}
-	
-	@Override
-	protected void process() {
-        LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "with state", state); //$NON-NLS-1$ //$NON-NLS-2$
-        try {
-            if (this.state == ProcessingState.NEW) {
-                state = ProcessingState.PROCESSING;
-        		processNew();
-                if (isCanceled) {
-                	this.processingException = new TeiidProcessingException(QueryPlugin.Util.getString("QueryProcessor.request_cancelled", this.requestID)); //$NON-NLS-1$
-                    state = ProcessingState.CLOSE;
-                } 
-        	}
-        	
-            resume();
-        	
-            if (this.state == ProcessingState.PROCESSING) {
-            	processMore();
-            	if (this.closeRequested) {
-            		this.state = ProcessingState.CLOSE;
-            	}
-            }                  	            
-        } catch (BlockedException e) {
-            LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "- processor blocked"); //$NON-NLS-1$ //$NON-NLS-2$
-        } catch (QueryProcessor.ExpiredTimeSliceException e) {
-            LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "- time slice expired"); //$NON-NLS-1$ //$NON-NLS-2$
-            this.moreWork();
-        } catch (Throwable e) {
-        	LogManager.logDetail(LogConstants.CTX_DQP, e, "Request Thread", requestID, "- error occurred"); //$NON-NLS-1$ //$NON-NLS-2$
-            
-            if (!isCanceled()) {
-            	dqpCore.logMMCommand(this, Event.ERROR, null);
-                //Case 5558: Differentiate between system level errors and
-                //processing errors.  Only log system level errors as errors, 
-                //log the processing errors as warnings only
-                if(e instanceof TeiidProcessingException) {                          
-                	Throwable cause = e;
-                	while (cause.getCause() != null && cause.getCause() != cause) {
-                		cause = cause.getCause();
-                	}
-                	StackTraceElement elem = cause.getStackTrace()[0];
-                    LogManager.logWarning(LogConstants.CTX_DQP, QueryPlugin.Util.getString("ProcessWorker.processing_error", e.getMessage(), requestID, e.getClass().getName(), elem)); //$NON-NLS-1$
-                }else {
-                    LogManager.logError(LogConstants.CTX_DQP, e, QueryPlugin.Util.getString("ProcessWorker.error", requestID)); //$NON-NLS-1$
-                }                                
-            }
-            
-            this.processingException = e;
-            this.state = ProcessingState.CLOSE;
-        } finally {
-        	if (this.state == ProcessingState.CLOSE && !isClosed) {
-        		attemptClose();
-        	} else if (isClosed) {
-        		/*
-        		 * since there may be a client waiting notify them of a problem
-        		 */
-        		if (this.processingException == null) {
-        			this.processingException = new IllegalStateException("Request is already closed"); //$NON-NLS-1$
-        		}
-        		sendError();
-        	}
-        	suspend();
-        }
-    }
-
-	private void resume() throws XATransactionException {
-		if (this.transactionState == TransactionState.ACTIVE && this.transactionContext.getTransaction() != null) {
-			this.transactionService.resume(this.transactionContext);
-		}
-	}
-
-	private void suspend() {
-		try {
-			this.transactionService.suspend(this.transactionContext);
-		} catch (XATransactionException e) {
-			LogManager.logDetail(LogConstants.CTX_DQP, e, "Error suspending active transaction"); //$NON-NLS-1$
-		}
-	}
-
-	protected void processMore() throws BlockedException, TeiidException {
-		if (!doneProducingBatches) {
-			this.processor.getContext().setTimeSliceEnd(System.currentTimeMillis() + this.processorTimeslice);
-			sendResultsIfNeeded(null);
-			collector.collectTuples();
-		}
-		if (doneProducingBatches) {
-			if (this.transactionState == TransactionState.ACTIVE) {
-				/*
-				 * TEIID-14 if we are done producing batches, then proactively close transactional 
-				 * executions even ones that were intentionally kept alive. this may 
-				 * break the read of a lob from a transactional source under a transaction 
-				 * if the source does not support holding the clob open after commit
-				 */
-	        	for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
-	        		if (connectorRequest.isTransactional()) {
-	        			connectorRequest.fullyCloseSource();
-	        		}
-	            }
-				this.transactionState = TransactionState.DONE;
-				if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
-					this.transactionService.commit(transactionContext);
-				} else {
-					suspend();
-				}
-			}
-			sendResultsIfNeeded(null);
-		} else {
-			moreWork(false); // If the timeslice expired, then the processor can probably produce more batches.
-			if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-				LogManager.logDetail(LogConstants.CTX_DQP, "############# PW EXITING on " + requestID + " - reenqueueing for more processing ###########"); //$NON-NLS-1$ //$NON-NLS-2$
-			}
-		}
-	}
-
-	/**
-	 * Client close is currently implemented as asynch.
-	 * Any errors that occur will not make it to the client, instead we just log them here.
-	 */
-	protected void attemptClose() {
-		int rowcount = -1;
-		if (this.resultsBuffer != null) {
-			if (this.processor != null) {
-				this.processor.closeProcessing();
-			
-				if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-			        LogManager.logDetail(LogConstants.CTX_DQP, "Removing tuplesource for the request " + requestID); //$NON-NLS-1$
-			    }
-				rowcount = resultsBuffer.getRowCount();
-				if (this.cid == null || !this.doneProducingBatches) {
-					resultsBuffer.remove();
-				}
-				
-				for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
-					connectorRequest.fullyCloseSource();
-			    }
-			}
-
-			this.resultsBuffer = null;
-			
-			for (LobWorkItem lobWorkItem : this.lobStreams.values()) {
-				lobWorkItem.close();
-			}
-		}
-
-		if (this.transactionState == TransactionState.ACTIVE) { 
-			this.transactionState = TransactionState.DONE;
-            if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
-				try {
-	        		this.transactionService.rollback(transactionContext);
-	            } catch (XATransactionException e1) {
-	                LogManager.logWarning(LogConstants.CTX_DQP, e1, QueryPlugin.Util.getString("ProcessWorker.failed_rollback")); //$NON-NLS-1$           
-	            } 
-			} else {
-				suspend();
-			}
-		}
-		
-		isClosed = true;
-
-		dqpCore.removeRequest(this);
-	    
-		if (this.processingException != null) {
-			sendError();			
-		} else {
-	        dqpCore.logMMCommand(this, Event.END, rowcount);
-		}
-	}
-
-	protected void processNew() throws TeiidProcessingException, TeiidComponentException {
-		SessionAwareCache<CachedResults> rsCache = dqpCore.getRsCache();
-		ParseInfo pi = Request.createParseInfo(requestMsg);
-		CacheID cacheId = new CacheID(this.dqpWorkContext, pi, requestMsg.getCommandString());
-    	boolean cachable = cacheId.setParameters(requestMsg.getParameterValues());
-		if (rsCache != null && cachable) {
-			CachedResults cr = rsCache.get(cacheId);
-			if (cr != null && (requestMsg.useResultSetCache() || cr.getHint() != null)) {
-				this.resultsBuffer = cr.getResults();
-				this.analysisRecord = cr.getAnalysisRecord();
-				request.initMetadata();
-				this.originalCommand = cr.getCommand(requestMsg.getCommandString(), request.metadata, pi);
-				request.validateAccess(this.originalCommand);
-				this.doneProducingBatches();
-				return;
-			}
-		}
-		request.processRequest();
-		originalCommand = request.userCommand;
-        if (cachable && (requestMsg.useResultSetCache() || originalCommand.getCacheHint() != null) && rsCache != null && originalCommand.areResultsCachable()) {
-        	this.cid = cacheId;
-        }
-		processor = request.processor;
-		resultsBuffer = processor.createTupleBuffer();
-		if (this.cid != null && originalCommand.getCacheHint() != null) {
-			resultsBuffer.setPrefersMemory(originalCommand.getCacheHint().getPrefersMemory());
-		}
-		collector = new BatchCollector(processor, resultsBuffer) {
-			protected void flushBatchDirect(TupleBatch batch, boolean add) throws TeiidComponentException,TeiidProcessingException {
-				boolean added = false;
-				if (cid != null || resultsBuffer.isLobs()) {
-					super.flushBatchDirect(batch, add);
-					added = true;
-				}
-				if (batch.getTerminationFlag()) {
-					doneProducingBatches();
-				}
-				if (doneProducingBatches && cid != null) {
-			    	int determinismLevel = processor.getContext().getDeterminismLevel();
-	            	CachedResults cr = new CachedResults();
-	            	cr.setCommand(originalCommand);
-	                cr.setAnalysisRecord(analysisRecord);
-	                cr.setResults(resultsBuffer);
-	                if (determinismLevel > FunctionMethod.SESSION_DETERMINISTIC) {
-	    				LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("RequestWorkItem.cache_nondeterministic", originalCommand)); //$NON-NLS-1$
-	    			}
-	                dqpCore.getRsCache().put(cid, determinismLevel, cr, originalCommand.getCacheHint() != null?originalCommand.getCacheHint().getTtl():null);
-			    }
-				add = sendResultsIfNeeded(batch);
-				if (!added) {
-					super.flushBatchDirect(batch, add);
-				}
-			}
-		};
-		resultsBuffer = collector.getTupleBuffer();
-		resultsBuffer.setForwardOnly(isForwardOnly());
-		analysisRecord = request.analysisRecord;
-		analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
-		transactionContext = request.transactionContext;
-		if (this.transactionContext != null && this.transactionContext.getTransactionType() != Scope.NONE) {
-			this.transactionState = TransactionState.ACTIVE;
-		}
-		if (requestMsg.isNoExec()) {
-		    doneProducingBatches();
-            resultsBuffer.close();
-            this.cid = null;
-		}
-	    this.returnsUpdateCount = request.returnsUpdateCount;
-		request = null;
-	}
-
-	/**
-	 * Send results if they have been requested.  This should only be called from the processing thread.
-	 */
-	protected boolean sendResultsIfNeeded(TupleBatch batch) throws TeiidComponentException {
-		ResultsMessage response = null;
-		ResultsReceiver<ResultsMessage> receiver = null;
-		boolean result = true;
-		synchronized (this) {
-			if (this.resultsReceiver == null
-					|| (this.begin > (batch != null?batch.getEndRow():this.resultsBuffer.getRowCount()) && !doneProducingBatches)
-					|| (this.transactionState == TransactionState.ACTIVE)) {
-				return result;
-			}
-		
-			if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-				LogManager.logDetail(LogConstants.CTX_DQP, "[RequestWorkItem.sendResultsIfNeeded] requestID:", requestID, "resultsID:", this.resultsBuffer, "done:", doneProducingBatches );   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			}
-	
-			//TODO: support fetching more than 1 batch
-			boolean fromBuffer = false;
-    		if (batch == null || !(batch.containsRow(this.begin) || (batch.getTerminationFlag() && batch.getEndRow() <= this.begin))) {
-	    		if (savedBatch != null && savedBatch.containsRow(this.begin)) {
-	    			batch = savedBatch;
-	    		} else {
-	    			batch = resultsBuffer.getBatch(begin);
-	    		}
-	    		savedBatch = null;
-	    		fromBuffer = true;
-	    	}
-    		int count = this.end - this.begin + 1;
-    		if (batch.getRowCount() > count) {
-    			int beginRow = Math.min(this.begin, batch.getEndRow() - count + 1);
-    			int endRow = Math.min(beginRow + count - 1, batch.getEndRow());
-    			boolean last = false;
-    			if (endRow == batch.getEndRow()) {
-    				last = batch.getTerminationFlag();
-    			} else if (fromBuffer && isForwardOnly()) {
-        			savedBatch = batch;
-    			}
-                List<List<?>> memoryRows = batch.getTuples();
-                batch = new TupleBatch(beginRow, memoryRows.subList(beginRow - batch.getBeginRow(), endRow - batch.getBeginRow() + 1));
-                batch.setTerminationFlag(last);
-    		} else if (!fromBuffer){
-    			result = !isForwardOnly();
-    		}
-	        int finalRowCount = this.resultsBuffer.isFinal()?this.resultsBuffer.getRowCount():(batch.getTerminationFlag()?batch.getEndRow():-1);
-	        
-	        response = createResultsMessage(batch.getAllTuples(), this.originalCommand.getProjectedSymbols());
-	        response.setFirstRow(batch.getBeginRow());
-	        response.setLastRow(batch.getEndRow());
-	        response.setUpdateResult(this.returnsUpdateCount);
-	        // set final row
-	        response.setFinalRow(finalRowCount);
-	
-	        // send any warnings with the response object
-	        List<Throwable> responseWarnings = new ArrayList<Throwable>();
-	        if (this.processor != null) {
-				List<Exception> currentWarnings = processor.getAndClearWarnings();
-			    if (currentWarnings != null) {
-			    	responseWarnings.addAll(currentWarnings);
-			    }
-	        }
-		    synchronized (warnings) {
-	        	responseWarnings.addAll(this.warnings);
-	        	this.warnings.clear();
-		    }
-	        response.setWarnings(responseWarnings);
-	        
-	        // If it is stored procedure, set parameters
-	        if (originalCommand instanceof StoredProcedure) {
-	        	StoredProcedure proc = (StoredProcedure)originalCommand;
-	        	if (proc.returnParameters()) {
-	        		response.setParameters(getParameterInfo(proc));
-	        	}
-	        }
-	        /*
-	         * mark the results sent at this point.
-	         * communication exceptions will be treated as non-recoverable 
-	         */
-            receiver = this.resultsReceiver;
-            this.resultsReceiver = null;    
-		}
-        receiver.receiveResults(response);
-        return result;
-	}
-    
-    public ResultsMessage createResultsMessage(List[] batch, List columnSymbols) {
-        String[] columnNames = new String[columnSymbols.size()];
-        String[] dataTypes = new String[columnSymbols.size()];
-
-        for(int i=0; i<columnSymbols.size(); i++) {
-            SingleElementSymbol symbol = (SingleElementSymbol) columnSymbols.get(i);
-            columnNames[i] = SingleElementSymbol.getShortName(symbol.getOutputName());
-            dataTypes[i] = DataTypeManager.getDataTypeName(symbol.getType());
-        }
-        ResultsMessage result = new ResultsMessage(requestMsg, batch, columnNames, dataTypes);
-        setAnalysisRecords(result);
-        return result;
-    }
-    
-	private void setAnalysisRecords(ResultsMessage response) {
-		if(analysisRecord != null) {
-        	if (requestMsg.getShowPlan() != ShowPlan.OFF) {
-        		if (processor != null) {
-        			analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
-        		}
-        		response.setPlanDescription(analysisRecord.getQueryPlan());
-	            response.setAnnotations(analysisRecord.getAnnotations());
-        	}
-            if (requestMsg.getShowPlan() == ShowPlan.DEBUG) {
-            	response.setDebugLog(analysisRecord.getDebugLog());
-            }
-        }
-	}
-
-    private void sendError() {
-    	synchronized (this) {
-    		if (this.resultsReceiver == null) {
-    			LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Unable to send error to client as results were already sent.", requestID); //$NON-NLS-1$
-    			return;
-    		}
-    	}
-		LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Sending error to client", requestID); //$NON-NLS-1$
-        ResultsMessage response = new ResultsMessage(requestMsg);
-        response.setException(processingException);
-        setAnalysisRecords(response);
-        resultsReceiver.receiveResults(response);
-    }
-
-    private static List<ParameterInfo> getParameterInfo(StoredProcedure procedure) {
-        List<ParameterInfo> paramInfos = new ArrayList<ParameterInfo>();
-        
-        for (SPParameter param : procedure.getParameters()) {
-            ParameterInfo info = new ParameterInfo(param.getParameterType(), param.getResultSetColumns().size());
-            paramInfos.add(info);
-        }
-        
-        return paramInfos;
-    }
-    
-    public void processLobChunkRequest(String id, int streamRequestId, ResultsReceiver<LobChunk> chunckReceiver) {
-    	LobWorkItem workItem = null;
-    	synchronized (lobStreams) {
-            workItem = this.lobStreams.get(new Integer(streamRequestId));
-            if (workItem == null) {
-            	workItem = new LobWorkItem(this, dqpCore, id, streamRequestId);
-            	lobStreams.put(new Integer(streamRequestId), workItem);
-            }
-		}
-    	workItem.setResultsReceiver(chunckReceiver);
-        dqpCore.addWork(workItem);
-    }
-    
-    public void removeLobStream(int streamRequestId) {
-        this.lobStreams.remove(new Integer(streamRequestId));
-    } 
-    
-    public boolean requestCancel() throws TeiidComponentException {
-    	synchronized (this) {
-        	if (this.isCanceled || this.closeRequested) {
-        		return false;
-        	}
-        	this.isCanceled = true;
-		}
-    	if (this.processor != null) {
-    		this.processor.requestCanceled();
-    	}
-    	
-        // Cancel Connector atomic requests 
-        try {
-        	for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
-                connectorRequest.cancelRequest();
-            }
-        } finally {
-        	try {
-	            if (transactionService != null) {
-	                try {
-	                    transactionService.cancelTransactions(requestID.getConnectionID(), true);
-	                } catch (XATransactionException err) {
-	                    throw new TeiidComponentException(err);
-	                }
-	            }
-        	} finally {
-        		this.moreWork();
-        	}
-        }
-        return true;
-    }
-    
-    public boolean requestAtomicRequestCancel(AtomicRequestID ari) throws TeiidComponentException {
-    	// in the case that this does not support partial results; cancel
-        // the original processor request.
-        if(!requestMsg.supportsPartialResults()) {
-        	return requestCancel();
-        }
-        
-        DataTierTupleSource connectorRequest = this.connectorInfo.get(ari);
-        if (connectorRequest != null) {
-	        connectorRequest.cancelRequest();
-        	return true;
-        }
-        
-		LogManager.logDetail(LogConstants.CTX_DQP, "Connector request not found. AtomicRequestID=", ari); //$NON-NLS-1$ 
-        return false;
-    }
-    
-    public void requestClose() throws TeiidComponentException {
-    	synchronized (this) {
-        	if (this.state == ProcessingState.CLOSE || this.closeRequested) {
-        		if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-        			LogManager.logDetail(LogConstants.CTX_DQP, "Request already closing" + requestID); //$NON-NLS-1$
-        		}
-        		return;
-        	}
-		}
-    	this.closeRequested = true;
-    	if (!this.doneProducingBatches) {
-    		this.requestCancel(); //pending work should be canceled for fastest clean up
-    	}
-    	this.moreWork();
-    }
-    
-    public void requestMore(int batchFirst, int batchLast, ResultsReceiver<ResultsMessage> receiver) {
-    	this.requestResults(batchFirst, batchLast, receiver);
-    	this.moreWork(); 
-    }
-    
-    public void closeAtomicRequest(AtomicRequestID atomicRequestId) {
-        connectorInfo.remove(atomicRequestId);
-        LogManager.logTrace(LogConstants.CTX_DQP, new Object[] {"closed atomic-request:", atomicRequestId});  //$NON-NLS-1$
-    }
-    
-	public void addConnectorRequest(AtomicRequestID atomicRequestId, DataTierTupleSource connInfo) {
-		connectorInfo.put(atomicRequestId, connInfo);
-	}
-    
-    /**
-	 * <p>This method add information to the warning on the work item for the given
-	 * <code>RequestID</code>. This method is called from <code>DataTierManager</code></p>
-	 */
-    public void addSourceFailureDetails(SourceWarning details) {
-    	synchronized (warnings) {
-			this.warnings.add(details);
-    	}
-	}
-        
-	boolean isCanceled() {
-		return isCanceled;
-	}
-	
-	Command getOriginalCommand() throws TeiidProcessingException {
-		if (this.originalCommand == null) {
-			if (this.processingException != null) {
-				throw new TeiidProcessingException(this.processingException);
-			} 
-			throw new IllegalStateException("Original command is not available"); //$NON-NLS-1$
-		}
-		return this.originalCommand;
-	}
-	
-	void setOriginalCommand(Command originalCommand) {
-		this.originalCommand = originalCommand;
-	}
-
-	TransactionContext getTransactionContext() {
-		return transactionContext;
-	}
-	
-	
-	Collection<DataTierTupleSource> getConnectorRequests() {
-		return new LinkedList<DataTierTupleSource>(this.connectorInfo.values());
-	}
-	
-	DataTierTupleSource getConnectorRequest(AtomicRequestID id) {
-		return this.connectorInfo.get(id);
-	}
-	
-	public List<TeiidException> getWarnings() {
-		return warnings;
-	}
-
-	@Override
-	public String toString() {
-		return this.requestID.toString();
-	}
-
-	public DQPWorkContext getDqpWorkContext() {
-		return dqpWorkContext;
-	}
-	
-	public long getProcessingTimestamp() {
-		return processingTimestamp;
-	}
-	
-	@Override
-	public void release() {
-		try {
-			requestCancel();
-		} catch (TeiidComponentException e) {
-			LogManager.logWarning(LogConstants.CTX_DQP, e, "Failed to cancel " + requestID); //$NON-NLS-1$
-		}
-	}
-
-	private void doneProducingBatches() {
-		this.doneProducingBatches = true;
-		dqpCore.finishProcessing(this);
-	}
-	
-	@Override
-	public int getPriority() {
-		return (closeRequested || isCanceled) ? 0 : 1000;
-	}
-	
-	@Override
-	public long getCreationTime() {
-		return processingTimestamp;
-	}
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,739 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.dqp.internal.process;
+
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.client.SourceWarning;
+import org.teiid.client.RequestMessage.ShowPlan;
+import org.teiid.client.lob.LobChunk;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.client.util.ResultsReceiver;
+import org.teiid.client.xa.XATransactionException;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
+import org.teiid.dqp.internal.process.ThreadReuseExecutor.PrioritizedRunnable;
+import org.teiid.dqp.message.AtomicRequestID;
+import org.teiid.dqp.message.RequestID;
+import org.teiid.dqp.service.TransactionContext;
+import org.teiid.dqp.service.TransactionService;
+import org.teiid.dqp.service.TransactionContext.Scope;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.logging.CommandLogMessage.Event;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.function.metadata.FunctionMethod;
+import org.teiid.query.parser.ParseInfo;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.BatchCollector;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+
+public class RequestWorkItem extends AbstractWorkItem implements PrioritizedRunnable {
+	
+	private enum ProcessingState {NEW, PROCESSING, CLOSE}
+	private ProcessingState state = ProcessingState.NEW;
+    
+	private enum TransactionState {NONE, ACTIVE, DONE}
+	private TransactionState transactionState = TransactionState.NONE;
+	
+	/*
+	 * Obtained at construction time 
+	 */
+	protected final DQPCore dqpCore;
+    final RequestMessage requestMsg;    
+    final RequestID requestID;
+    private Request request; //provides the processing plan, held on a temporary basis
+    private final int processorTimeslice;
+	private CacheID cid;
+	private final TransactionService transactionService;
+	private final DQPWorkContext dqpWorkContext;
+	boolean active;
+	
+    /*
+     * obtained during new
+     */
+    private volatile QueryProcessor processor;
+    private BatchCollector collector;
+    private Command originalCommand;
+    private AnalysisRecord analysisRecord;
+    private TransactionContext transactionContext;
+    TupleBuffer resultsBuffer;
+    private boolean returnsUpdateCount;
+    
+    /*
+     * maintained during processing
+     */
+    private Throwable processingException;
+    private Map<AtomicRequestID, DataTierTupleSource> connectorInfo = new ConcurrentHashMap<AtomicRequestID, DataTierTupleSource>(4);
+    // This exception contains details of all the atomic requests that failed when query is run in partial results mode.
+    private List<TeiidException> warnings = new LinkedList<TeiidException>();
+    private volatile boolean doneProducingBatches;
+    private volatile boolean isClosed;
+    private volatile boolean isCanceled;
+    private volatile boolean closeRequested;
+
+	//results request
+	private ResultsReceiver<ResultsMessage> resultsReceiver;
+	private int begin;
+	private int end;
+    private TupleBatch savedBatch;
+    private Map<Integer, LobWorkItem> lobStreams = new ConcurrentHashMap<Integer, LobWorkItem>(4);    
+    
+    /**The time when command begins processing on the server.*/
+    private long processingTimestamp = System.currentTimeMillis();
+    
+    public RequestWorkItem(DQPCore dqpCore, RequestMessage requestMsg, Request request, ResultsReceiver<ResultsMessage> receiver, RequestID requestID, DQPWorkContext workContext) {
+        this.requestMsg = requestMsg;
+        this.requestID = requestID;
+        this.processorTimeslice = dqpCore.getProcessorTimeSlice();
+        this.transactionService = dqpCore.getTransactionService();
+        this.dqpCore = dqpCore;
+        this.request = request;
+        this.dqpWorkContext = workContext;
+        this.requestResults(1, requestMsg.getFetchSize(), receiver);
+    }
+    
+    private boolean isForwardOnly() {
+    	return this.cid == null && requestMsg.getCursorType() == ResultSet.TYPE_FORWARD_ONLY;    	
+    }
+    
+	/**
+	 * Ask for results.
+	 * @param beginRow
+	 * @param endRow
+	 */
+    synchronized void requestResults(int beginRow, int endRow, ResultsReceiver<ResultsMessage> receiver) {
+		if (this.resultsReceiver != null) {
+			throw new IllegalStateException("Results already requested"); //$NON-NLS-1$\
+		}
+		this.resultsReceiver = receiver;
+		this.begin = beginRow;
+		this.end = endRow;
+	}
+    
+	@Override
+	protected boolean isDoneProcessing() {
+		return isClosed;
+	}
+
+	@Override
+	protected void resumeProcessing() {
+		if (doneProducingBatches && !closeRequested && !isCanceled) {
+			this.run(); // just run in the IO thread
+		} else {
+			dqpCore.addWork(this);
+		}
+	}
+	
+	@Override
+	protected void process() {
+        LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "with state", state); //$NON-NLS-1$ //$NON-NLS-2$
+        try {
+            if (this.state == ProcessingState.NEW) {
+                state = ProcessingState.PROCESSING;
+        		processNew();
+                if (isCanceled) {
+                	this.processingException = new TeiidProcessingException(QueryPlugin.Util.getString("QueryProcessor.request_cancelled", this.requestID)); //$NON-NLS-1$
+                    state = ProcessingState.CLOSE;
+                } 
+        	}
+        	
+            resume();
+        	
+            if (this.state == ProcessingState.PROCESSING) {
+            	processMore();
+            	if (this.closeRequested) {
+            		this.state = ProcessingState.CLOSE;
+            	}
+            }                  	            
+        } catch (BlockedException e) {
+            LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "- processor blocked"); //$NON-NLS-1$ //$NON-NLS-2$
+        } catch (QueryProcessor.ExpiredTimeSliceException e) {
+            LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "- time slice expired"); //$NON-NLS-1$ //$NON-NLS-2$
+            this.moreWork();
+        } catch (Throwable e) {
+        	LogManager.logDetail(LogConstants.CTX_DQP, e, "Request Thread", requestID, "- error occurred"); //$NON-NLS-1$ //$NON-NLS-2$
+            
+            if (!isCanceled()) {
+            	dqpCore.logMMCommand(this, Event.ERROR, null);
+                //Case 5558: Differentiate between system level errors and
+                //processing errors.  Only log system level errors as errors, 
+                //log the processing errors as warnings only
+                if(e instanceof TeiidProcessingException) {                          
+                	Throwable cause = e;
+                	while (cause.getCause() != null && cause.getCause() != cause) {
+                		cause = cause.getCause();
+                	}
+                	StackTraceElement elem = cause.getStackTrace()[0];
+                    LogManager.logWarning(LogConstants.CTX_DQP, QueryPlugin.Util.getString("ProcessWorker.processing_error", e.getMessage(), requestID, e.getClass().getName(), elem)); //$NON-NLS-1$
+                }else {
+                    LogManager.logError(LogConstants.CTX_DQP, e, QueryPlugin.Util.getString("ProcessWorker.error", requestID)); //$NON-NLS-1$
+                }                                
+            }
+            
+            this.processingException = e;
+            this.state = ProcessingState.CLOSE;
+        } finally {
+        	if (this.state == ProcessingState.CLOSE && !isClosed) {
+        		attemptClose();
+        	} else if (isClosed) {
+        		/*
+        		 * since there may be a client waiting notify them of a problem
+        		 */
+        		if (this.processingException == null) {
+        			this.processingException = new IllegalStateException("Request is already closed"); //$NON-NLS-1$
+        		}
+        		sendError();
+        	}
+        	suspend();
+        }
+    }
+
+	private void resume() throws XATransactionException {
+		if (this.transactionState == TransactionState.ACTIVE && this.transactionContext.getTransaction() != null) {
+			this.transactionService.resume(this.transactionContext);
+		}
+	}
+
+	private void suspend() {
+		try {
+			this.transactionService.suspend(this.transactionContext);
+		} catch (XATransactionException e) {
+			LogManager.logDetail(LogConstants.CTX_DQP, e, "Error suspending active transaction"); //$NON-NLS-1$
+		}
+	}
+
+	protected void processMore() throws BlockedException, TeiidException {
+		if (!doneProducingBatches) {
+			this.processor.getContext().setTimeSliceEnd(System.currentTimeMillis() + this.processorTimeslice);
+			sendResultsIfNeeded(null);
+			collector.collectTuples();
+		}
+		if (doneProducingBatches) {
+			if (this.transactionState == TransactionState.ACTIVE) {
+				/*
+				 * TEIID-14 if we are done producing batches, then proactively close transactional 
+				 * executions even ones that were intentionally kept alive. this may 
+				 * break the read of a lob from a transactional source under a transaction 
+				 * if the source does not support holding the clob open after commit
+				 */
+	        	for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
+	        		if (connectorRequest.isTransactional()) {
+	        			connectorRequest.fullyCloseSource();
+	        		}
+	            }
+				this.transactionState = TransactionState.DONE;
+				if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
+					this.transactionService.commit(transactionContext);
+				} else {
+					suspend();
+				}
+			}
+			sendResultsIfNeeded(null);
+		} else {
+			moreWork(false); // If the timeslice expired, then the processor can probably produce more batches.
+			if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+				LogManager.logDetail(LogConstants.CTX_DQP, "############# PW EXITING on " + requestID + " - reenqueueing for more processing ###########"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		}
+	}
+
+	/**
+	 * Client close is currently implemented as asynch.
+	 * Any errors that occur will not make it to the client, instead we just log them here.
+	 */
+	protected void attemptClose() {
+		int rowcount = -1;
+		if (this.resultsBuffer != null) {
+			if (this.processor != null) {
+				this.processor.closeProcessing();
+			
+				if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+			        LogManager.logDetail(LogConstants.CTX_DQP, "Removing tuplesource for the request " + requestID); //$NON-NLS-1$
+			    }
+				rowcount = resultsBuffer.getRowCount();
+				if (this.cid == null || !this.doneProducingBatches) {
+					resultsBuffer.remove();
+				}
+				
+				for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
+					connectorRequest.fullyCloseSource();
+			    }
+			}
+
+			this.resultsBuffer = null;
+			
+			for (LobWorkItem lobWorkItem : this.lobStreams.values()) {
+				lobWorkItem.close();
+			}
+		}
+
+		if (this.transactionState == TransactionState.ACTIVE) { 
+			this.transactionState = TransactionState.DONE;
+            if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
+				try {
+	        		this.transactionService.rollback(transactionContext);
+	            } catch (XATransactionException e1) {
+	                LogManager.logWarning(LogConstants.CTX_DQP, e1, QueryPlugin.Util.getString("ProcessWorker.failed_rollback")); //$NON-NLS-1$           
+	            } 
+			} else {
+				suspend();
+			}
+		}
+		
+		isClosed = true;
+
+		dqpCore.removeRequest(this);
+	    
+		if (this.processingException != null) {
+			sendError();			
+		} else {
+	        dqpCore.logMMCommand(this, Event.END, rowcount);
+		}
+	}
+
+	protected void processNew() throws TeiidProcessingException, TeiidComponentException {
+		SessionAwareCache<CachedResults> rsCache = dqpCore.getRsCache();
+				
+		boolean cachable = false;
+		CacheID cacheId = null;
+		boolean canUseCached = (requestMsg.useResultSetCache() || 
+				QueryParser.getQueryParser().parseCacheHint(requestMsg.getCommandString()) != null);
+		
+		if (rsCache != null) {
+			if (!canUseCached) {
+				LogManager.logDetail(LogConstants.CTX_DQP, requestID, "No cache directive"); //$NON-NLS-1$
+			} else {
+				ParseInfo pi = Request.createParseInfo(requestMsg);
+				cacheId = new CacheID(this.dqpWorkContext, pi, requestMsg.getCommandString());
+		    	cachable = cacheId.setParameters(requestMsg.getParameterValues());
+				if (cachable) {
+					CachedResults cr = rsCache.get(cacheId);
+					if (cr != null) {
+						this.resultsBuffer = cr.getResults();
+						this.analysisRecord = cr.getAnalysisRecord();
+						request.initMetadata();
+						this.originalCommand = cr.getCommand(requestMsg.getCommandString(), request.metadata, pi);
+						request.validateAccess(this.originalCommand);
+						this.doneProducingBatches();
+						return;
+					} 
+				} else {
+					LogManager.logDetail(LogConstants.CTX_DQP, requestID, "Parameters are not serializable - cache cannot be used for", cacheId); //$NON-NLS-1$
+				}
+			}
+		}
+		request.processRequest();
+		originalCommand = request.userCommand;
+        if (cachable && (requestMsg.useResultSetCache() || originalCommand.getCacheHint() != null) && rsCache != null && originalCommand.areResultsCachable()) {
+        	this.cid = cacheId;
+        }
+		processor = request.processor;
+		resultsBuffer = processor.createTupleBuffer();
+		if (this.cid != null && originalCommand.getCacheHint() != null) {
+			LogManager.logDetail(LogConstants.CTX_DQP, requestID, "Using cache hint", originalCommand.getCacheHint()); //$NON-NLS-1$
+			resultsBuffer.setPrefersMemory(originalCommand.getCacheHint().getPrefersMemory());
+		}
+		collector = new BatchCollector(processor, resultsBuffer) {
+			protected void flushBatchDirect(TupleBatch batch, boolean add) throws TeiidComponentException,TeiidProcessingException {
+				boolean added = false;
+				if (cid != null || resultsBuffer.isLobs()) {
+					super.flushBatchDirect(batch, add);
+					added = true;
+				}
+				if (batch.getTerminationFlag()) {
+					doneProducingBatches();
+				}
+				if (doneProducingBatches && cid != null) {
+			    	int determinismLevel = processor.getContext().getDeterminismLevel();
+	            	CachedResults cr = new CachedResults();
+	            	cr.setCommand(originalCommand);
+	                cr.setAnalysisRecord(analysisRecord);
+	                cr.setResults(resultsBuffer);
+	                if (determinismLevel > FunctionMethod.SESSION_DETERMINISTIC) {
+	    				LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("RequestWorkItem.cache_nondeterministic", originalCommand)); //$NON-NLS-1$
+	    			}
+	                dqpCore.getRsCache().put(cid, determinismLevel, cr, originalCommand.getCacheHint() != null?originalCommand.getCacheHint().getTtl():null);
+			    }
+				add = sendResultsIfNeeded(batch);
+				if (!added) {
+					super.flushBatchDirect(batch, add);
+				}
+			}
+		};
+		resultsBuffer = collector.getTupleBuffer();
+		resultsBuffer.setForwardOnly(isForwardOnly());
+		analysisRecord = request.analysisRecord;
+		analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
+		transactionContext = request.transactionContext;
+		if (this.transactionContext != null && this.transactionContext.getTransactionType() != Scope.NONE) {
+			this.transactionState = TransactionState.ACTIVE;
+		}
+		if (requestMsg.isNoExec()) {
+		    doneProducingBatches();
+            resultsBuffer.close();
+            this.cid = null;
+		}
+	    this.returnsUpdateCount = request.returnsUpdateCount;
+		request = null;
+	}
+
+	/**
+	 * Send results if they have been requested.  This should only be called from the processing thread.
+	 */
+	protected boolean sendResultsIfNeeded(TupleBatch batch) throws TeiidComponentException {
+		ResultsMessage response = null;
+		ResultsReceiver<ResultsMessage> receiver = null;
+		boolean result = true;
+		synchronized (this) {
+			if (this.resultsReceiver == null
+					|| (this.begin > (batch != null?batch.getEndRow():this.resultsBuffer.getRowCount()) && !doneProducingBatches)
+					|| (this.transactionState == TransactionState.ACTIVE)) {
+				return result;
+			}
+		
+			if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+				LogManager.logDetail(LogConstants.CTX_DQP, "[RequestWorkItem.sendResultsIfNeeded] requestID:", requestID, "resultsID:", this.resultsBuffer, "done:", doneProducingBatches );   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			}
+	
+			//TODO: support fetching more than 1 batch
+			boolean fromBuffer = false;
+    		if (batch == null || !(batch.containsRow(this.begin) || (batch.getTerminationFlag() && batch.getEndRow() <= this.begin))) {
+	    		if (savedBatch != null && savedBatch.containsRow(this.begin)) {
+	    			batch = savedBatch;
+	    		} else {
+	    			batch = resultsBuffer.getBatch(begin);
+	    		}
+	    		savedBatch = null;
+	    		fromBuffer = true;
+	    	}
+    		int count = this.end - this.begin + 1;
+    		if (batch.getRowCount() > count) {
+    			int beginRow = Math.min(this.begin, batch.getEndRow() - count + 1);
+    			int endRow = Math.min(beginRow + count - 1, batch.getEndRow());
+    			boolean last = false;
+    			if (endRow == batch.getEndRow()) {
+    				last = batch.getTerminationFlag();
+    			} else if (fromBuffer && isForwardOnly()) {
+        			savedBatch = batch;
+    			}
+                List<List<?>> memoryRows = batch.getTuples();
+                batch = new TupleBatch(beginRow, memoryRows.subList(beginRow - batch.getBeginRow(), endRow - batch.getBeginRow() + 1));
+                batch.setTerminationFlag(last);
+    		} else if (!fromBuffer){
+    			result = !isForwardOnly();
+    		}
+	        int finalRowCount = this.resultsBuffer.isFinal()?this.resultsBuffer.getRowCount():(batch.getTerminationFlag()?batch.getEndRow():-1);
+	        
+	        response = createResultsMessage(batch.getAllTuples(), this.originalCommand.getProjectedSymbols());
+	        response.setFirstRow(batch.getBeginRow());
+	        response.setLastRow(batch.getEndRow());
+	        response.setUpdateResult(this.returnsUpdateCount);
+	        // set final row
+	        response.setFinalRow(finalRowCount);
+	
+	        // send any warnings with the response object
+	        List<Throwable> responseWarnings = new ArrayList<Throwable>();
+	        if (this.processor != null) {
+				List<Exception> currentWarnings = processor.getAndClearWarnings();
+			    if (currentWarnings != null) {
+			    	responseWarnings.addAll(currentWarnings);
+			    }
+	        }
+		    synchronized (warnings) {
+	        	responseWarnings.addAll(this.warnings);
+	        	this.warnings.clear();
+		    }
+	        response.setWarnings(responseWarnings);
+	        
+	        // If it is stored procedure, set parameters
+	        if (originalCommand instanceof StoredProcedure) {
+	        	StoredProcedure proc = (StoredProcedure)originalCommand;
+	        	if (proc.returnParameters()) {
+	        		response.setParameters(getParameterInfo(proc));
+	        	}
+	        }
+	        /*
+	         * mark the results sent at this point.
+	         * communication exceptions will be treated as non-recoverable 
+	         */
+            receiver = this.resultsReceiver;
+            this.resultsReceiver = null;    
+		}
+        receiver.receiveResults(response);
+        return result;
+	}
+    
+    public ResultsMessage createResultsMessage(List[] batch, List columnSymbols) {
+        String[] columnNames = new String[columnSymbols.size()];
+        String[] dataTypes = new String[columnSymbols.size()];
+
+        for(int i=0; i<columnSymbols.size(); i++) {
+            SingleElementSymbol symbol = (SingleElementSymbol) columnSymbols.get(i);
+            columnNames[i] = SingleElementSymbol.getShortName(symbol.getOutputName());
+            dataTypes[i] = DataTypeManager.getDataTypeName(symbol.getType());
+        }
+        ResultsMessage result = new ResultsMessage(requestMsg, batch, columnNames, dataTypes);
+        setAnalysisRecords(result);
+        return result;
+    }
+    
+	private void setAnalysisRecords(ResultsMessage response) {
+		if(analysisRecord != null) {
+        	if (requestMsg.getShowPlan() != ShowPlan.OFF) {
+        		if (processor != null) {
+        			analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
+        		}
+        		response.setPlanDescription(analysisRecord.getQueryPlan());
+	            response.setAnnotations(analysisRecord.getAnnotations());
+        	}
+            if (requestMsg.getShowPlan() == ShowPlan.DEBUG) {
+            	response.setDebugLog(analysisRecord.getDebugLog());
+            }
+        }
+	}
+
+    private void sendError() {
+    	synchronized (this) {
+    		if (this.resultsReceiver == null) {
+    			LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Unable to send error to client as results were already sent.", requestID); //$NON-NLS-1$
+    			return;
+    		}
+    	}
+		LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Sending error to client", requestID); //$NON-NLS-1$
+        ResultsMessage response = new ResultsMessage(requestMsg);
+        response.setException(processingException);
+        setAnalysisRecords(response);
+        resultsReceiver.receiveResults(response);
+    }
+
+    private static List<ParameterInfo> getParameterInfo(StoredProcedure procedure) {
+        List<ParameterInfo> paramInfos = new ArrayList<ParameterInfo>();
+        
+        for (SPParameter param : procedure.getParameters()) {
+            ParameterInfo info = new ParameterInfo(param.getParameterType(), param.getResultSetColumns().size());
+            paramInfos.add(info);
+        }
+        
+        return paramInfos;
+    }
+    
+    public void processLobChunkRequest(String id, int streamRequestId, ResultsReceiver<LobChunk> chunckReceiver) {
+    	LobWorkItem workItem = null;
+    	synchronized (lobStreams) {
+            workItem = this.lobStreams.get(new Integer(streamRequestId));
+            if (workItem == null) {
+            	workItem = new LobWorkItem(this, dqpCore, id, streamRequestId);
+            	lobStreams.put(new Integer(streamRequestId), workItem);
+            }
+		}
+    	workItem.setResultsReceiver(chunckReceiver);
+        dqpCore.addWork(workItem);
+    }
+    
+    public void removeLobStream(int streamRequestId) {
+        this.lobStreams.remove(new Integer(streamRequestId));
+    } 
+    
+    public boolean requestCancel() throws TeiidComponentException {
+    	synchronized (this) {
+        	if (this.isCanceled || this.closeRequested) {
+        		return false;
+        	}
+        	this.isCanceled = true;
+		}
+    	if (this.processor != null) {
+    		this.processor.requestCanceled();
+    	}
+    	
+        // Cancel Connector atomic requests 
+        try {
+        	for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
+                connectorRequest.cancelRequest();
+            }
+        } finally {
+        	try {
+	            if (transactionService != null) {
+	                try {
+	                    transactionService.cancelTransactions(requestID.getConnectionID(), true);
+	                } catch (XATransactionException err) {
+	                    throw new TeiidComponentException(err);
+	                }
+	            }
+        	} finally {
+        		this.moreWork();
+        	}
+        }
+        return true;
+    }
+    
+    public boolean requestAtomicRequestCancel(AtomicRequestID ari) throws TeiidComponentException {
+    	// in the case that this does not support partial results; cancel
+        // the original processor request.
+        if(!requestMsg.supportsPartialResults()) {
+        	return requestCancel();
+        }
+        
+        DataTierTupleSource connectorRequest = this.connectorInfo.get(ari);
+        if (connectorRequest != null) {
+	        connectorRequest.cancelRequest();
+        	return true;
+        }
+        
+		LogManager.logDetail(LogConstants.CTX_DQP, "Connector request not found. AtomicRequestID=", ari); //$NON-NLS-1$ 
+        return false;
+    }
+    
+    public void requestClose() throws TeiidComponentException {
+    	synchronized (this) {
+        	if (this.state == ProcessingState.CLOSE || this.closeRequested) {
+        		if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+        			LogManager.logDetail(LogConstants.CTX_DQP, "Request already closing" + requestID); //$NON-NLS-1$
+        		}
+        		return;
+        	}
+		}
+    	this.closeRequested = true;
+    	if (!this.doneProducingBatches) {
+    		this.requestCancel(); //pending work should be canceled for fastest clean up
+    	}
+    	this.moreWork();
+    }
+    
+    public void requestMore(int batchFirst, int batchLast, ResultsReceiver<ResultsMessage> receiver) {
+    	this.requestResults(batchFirst, batchLast, receiver);
+    	this.moreWork(); 
+    }
+    
+    public void closeAtomicRequest(AtomicRequestID atomicRequestId) {
+        connectorInfo.remove(atomicRequestId);
+        LogManager.logTrace(LogConstants.CTX_DQP, new Object[] {"closed atomic-request:", atomicRequestId});  //$NON-NLS-1$
+    }
+    
+	public void addConnectorRequest(AtomicRequestID atomicRequestId, DataTierTupleSource connInfo) {
+		connectorInfo.put(atomicRequestId, connInfo);
+	}
+    
+    /**
+	 * <p>This method add information to the warning on the work item for the given
+	 * <code>RequestID</code>. This method is called from <code>DataTierManager</code></p>
+	 */
+    public void addSourceFailureDetails(SourceWarning details) {
+    	synchronized (warnings) {
+			this.warnings.add(details);
+    	}
+	}
+        
+	boolean isCanceled() {
+		return isCanceled;
+	}
+	
+	Command getOriginalCommand() throws TeiidProcessingException {
+		if (this.originalCommand == null) {
+			if (this.processingException != null) {
+				throw new TeiidProcessingException(this.processingException);
+			} 
+			throw new IllegalStateException("Original command is not available"); //$NON-NLS-1$
+		}
+		return this.originalCommand;
+	}
+	
+	void setOriginalCommand(Command originalCommand) {
+		this.originalCommand = originalCommand;
+	}
+
+	TransactionContext getTransactionContext() {
+		return transactionContext;
+	}
+	
+	
+	Collection<DataTierTupleSource> getConnectorRequests() {
+		return new LinkedList<DataTierTupleSource>(this.connectorInfo.values());
+	}
+	
+	DataTierTupleSource getConnectorRequest(AtomicRequestID id) {
+		return this.connectorInfo.get(id);
+	}
+	
+	public List<TeiidException> getWarnings() {
+		return warnings;
+	}
+
+	@Override
+	public String toString() {
+		return this.requestID.toString();
+	}
+
+	public DQPWorkContext getDqpWorkContext() {
+		return dqpWorkContext;
+	}
+	
+	public long getProcessingTimestamp() {
+		return processingTimestamp;
+	}
+	
+	@Override
+	public void release() {
+		try {
+			requestCancel();
+		} catch (TeiidComponentException e) {
+			LogManager.logWarning(LogConstants.CTX_DQP, e, "Failed to cancel " + requestID); //$NON-NLS-1$
+		}
+	}
+
+	private void doneProducingBatches() {
+		this.doneProducingBatches = true;
+		dqpCore.finishProcessing(this);
+	}
+	
+	@Override
+	public int getPriority() {
+		return (closeRequested || isCanceled) ? 0 : 1000;
+	}
+	
+	@Override
+	public long getCreationTime() {
+		return processingTimestamp;
+	}
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,296 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.dqp.internal.process;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.teiid.cache.Cachable;
-import org.teiid.cache.Cache;
-import org.teiid.cache.CacheConfiguration;
-import org.teiid.cache.CacheFactory;
-import org.teiid.cache.DefaultCache;
-import org.teiid.cache.DefaultCacheFactory;
-import org.teiid.cache.CacheConfiguration.Policy;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.core.util.HashCodeUtil;
-import org.teiid.query.function.metadata.FunctionMethod;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.vdb.runtime.VDBKey;
-
-
-/**
- * This class is used to cache session aware objects
- */
-public class SessionAwareCache<T> {
-	public static final int DEFAULT_MAX_SIZE_TOTAL = 512;
-
-	private Cache<CacheID, T> localCache;
-	private Cache<CacheID, T> distributedCache;
-	private Cache tupleBatchCache;
-	
-	private int maxSize = DEFAULT_MAX_SIZE_TOTAL;
-	
-	private AtomicInteger cacheHit = new AtomicInteger();
-	private AtomicInteger totalRequests = new AtomicInteger();
-	
-	private BufferManager bufferManager;
-	
-	public SessionAwareCache(){
-		this(DEFAULT_MAX_SIZE_TOTAL);
-	}
-	
-	SessionAwareCache(int maxSize){
-		this(new DefaultCacheFactory(), Cache.Type.RESULTSET, new CacheConfiguration(Policy.LRU, 60, maxSize));
-	}
-	
-	SessionAwareCache (final CacheFactory cacheFactory, final Cache.Type type, final CacheConfiguration config){
-		this.maxSize = config.getMaxEntries();
-		if(this.maxSize < 0){
-			this.maxSize = DEFAULT_MAX_SIZE_TOTAL;
-		}		
-		this.localCache = new DefaultCache<CacheID, T>("local", maxSize, config.getMaxAgeInSeconds()*1000); //$NON-NLS-1$
-		
-		if (type == Cache.Type.PREPAREDPLAN) {
-			this.distributedCache = localCache;
-		}
-		else {
-			this.distributedCache = cacheFactory.get(type, config);
-			if (type == Cache.Type.RESULTSET) {
-				this.tupleBatchCache = cacheFactory.get(Cache.Type.RESULTSET_BATCHES, config);
-			}
-			else {
-				this.tupleBatchCache = this.distributedCache;
-			}
-		}
-	}	
-	
-	public T get(CacheID id){
-
-		this.totalRequests.getAndIncrement();
-		
-		id.setSessionId(id.originalSessionId);
-		T result = localCache.get(id);
-		
-		if (result == null) {
-			id.setSessionId(null);
-			
-			id.setUserName(id.originalUserName);
-			result = distributedCache.get(id);
-			
-			if (result == null) {
-				id.setUserName(null);
-				result = distributedCache.get(id);
-			}
-			
-			if (result != null && result instanceof Cachable) {
-				Cachable c = (Cachable)result;
-				if (!c.restore(this.tupleBatchCache, this.bufferManager)) {
-					result = null;
-				}
-			}
-		}
-		
-		if (result != null) {
-			cacheHit.getAndIncrement();
-		}
-		return result;
-	}
-	
-	public int getCacheHitCount() {
-		return cacheHit.get();
-	}
-		
-	public int getRequestCount() {
-		return this.totalRequests.get();
-	}
-	
-	public int getTotalCacheEntries() {
-		if (this.localCache == this.distributedCache) {
-			return this.localCache.size();
-		}
-		return localCache.size() + distributedCache.size();
-	}
-	
-	public void put(CacheID id, int determinismLevel, T t, Long ttl){
-		if (determinismLevel >= FunctionMethod.SESSION_DETERMINISTIC) {
-			id.setSessionId(id.originalSessionId);
-			this.localCache.put(id, t, ttl);
-		} 
-		else {
-			
-			boolean insert = true;
-			
-			id.setSessionId(null);
-			
-			if (determinismLevel == FunctionMethod.USER_DETERMINISTIC) {
-				id.setUserName(id.originalUserName);
-			}
-			else {
-				id.setUserName(null);
-			}
-			
-			if (t instanceof Cachable) {
-				Cachable c = (Cachable)t;
-				insert = c.prepare(this.tupleBatchCache, this.bufferManager);
-			}
-			
-			if (insert) {
-				this.distributedCache.put(id, t, ttl);
-			}
-		}
-	}
-	
-	/**
-	 * Clear all the cached plans for all the clientConns
-	 * @param clientConn ClientConnection
-	 */
-	public void clearAll(){
-		this.localCache.clear();
-		this.distributedCache.clear();
-	}	
-	
-	public void clearForVDB(String vdbName, int version) {
-		clearCache(this.localCache, vdbName, version);
-		clearCache(this.distributedCache, vdbName, version);
-	}
-	
-	private void clearCache(Cache<CacheID, T> cache, String vdbName, int version) {
-		Set<CacheID> keys = cache.keys();
-		VDBKey vdbKey = new VDBKey(vdbName, version);
-		for (CacheID key:keys) {
-			if (key.vdbInfo.equals(vdbKey)) {
-				cache.remove(key);
-			}
-		}
-	}
-	
-	public static class CacheID implements Serializable {
-		private static final long serialVersionUID = 8261905111156764744L;
-		private String sql;
-		private VDBKey vdbInfo;
-		private ParseInfo pi;
-		private String sessionId;
-		private String originalSessionId;
-		private List<Serializable> parameters;
-		private String userName;
-		private String originalUserName;
-		
-		public CacheID(DQPWorkContext context, ParseInfo pi, String sql){
-			this(pi, sql, context.getVdbName(), context.getVdbVersion(), context.getSessionId(), context.getUserName());
-		}
-		
-		public CacheID(ParseInfo pi, String sql, String vdbName, int vdbVersion, String sessionId, String userName){
-			this.sql = sql;
-			this.vdbInfo = new VDBKey(vdbName, vdbVersion);
-			this.pi = pi;
-			this.originalSessionId = sessionId;
-			this.originalUserName = userName;
-		}
-
-		
-		public String getSessionId() {
-			return sessionId;
-		}
-		
-		public String getUserName() {
-			return userName;
-		}
-		
-		private void setSessionId(String sessionId) {
-			this.sessionId = sessionId;
-		}
-		
-		/**
-		 * Set the raw (non-Constant) parameter values.
-		 * @param parameters
-		 * @return
-		 */
-		public boolean setParameters(List<?> parameters) {
-			if (parameters !=  null && !parameters.isEmpty()) {
-				this.parameters = new ArrayList<Serializable>();
-				for (Object obj:parameters) {
-					if (obj == null) {
-						this.parameters.add(null);
-						continue;
-					}
-					if (!(obj instanceof Serializable)) {
-						return false;
-					}
-					
-					Class<?> type = DataTypeManager.determineDataTypeClass(obj);
-					if (DataTypeManager.isLOB(type) || type == DataTypeManager.DefaultDataClasses.OBJECT) {
-						return false;
-					}
-					this.parameters.add((Serializable)obj);
-				}
-			}
-			return true;
-		}
-		
-		public String getSql() {
-			return sql;
-		}
-		
-		void setUserName(String name) {
-			this.userName = name;
-		}
-						
-		public boolean equals(Object obj){
-	        if(obj == this) {
-	            return true;
-	        } 
-	        if(! (obj instanceof CacheID)) {
-	            return false;
-	        } 
-        	CacheID that = (CacheID)obj;
-            return EquivalenceUtil.areEqual(this.pi, that.pi) && this.vdbInfo.equals(that.vdbInfo) && this.sql.equals(that.sql) 
-            	&& EquivalenceUtil.areEqual(this.userName, that.userName)            	
-            	&& EquivalenceUtil.areEqual(this.sessionId, that.sessionId)
-            	&& EquivalenceUtil.areEqual(this.parameters, that.parameters);
-		}
-		
-	    public int hashCode() {
-	        return HashCodeUtil.hashCode(0, vdbInfo, sql, pi, this.userName, sessionId, parameters);
-	    }
-	    
-	    @Override
-	    public String toString() {
-	    	return "Cache Entry<" + originalSessionId + "="+ originalUserName + "> params:" + parameters + " sql:" + sql; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	    }
-	    
-	}
-	
-    int getSpaceAllowed() {
-        return maxSize;
-    }
-    
-    public void setBufferManager(BufferManager bufferManager) {
-    	this.bufferManager = bufferManager;
-    }
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,305 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.dqp.internal.process;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.teiid.cache.Cachable;
+import org.teiid.cache.Cache;
+import org.teiid.cache.CacheConfiguration;
+import org.teiid.cache.CacheFactory;
+import org.teiid.cache.DefaultCache;
+import org.teiid.cache.DefaultCacheFactory;
+import org.teiid.cache.CacheConfiguration.Policy;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.query.function.metadata.FunctionMethod;
+import org.teiid.query.parser.ParseInfo;
+import org.teiid.vdb.runtime.VDBKey;
+
+
+/**
+ * This class is used to cache session aware objects
+ */
+public class SessionAwareCache<T> {
+	public static final int DEFAULT_MAX_SIZE_TOTAL = 512;
+
+	private Cache<CacheID, T> localCache;
+	private Cache<CacheID, T> distributedCache;
+	private Cache tupleBatchCache;
+	
+	private int maxSize = DEFAULT_MAX_SIZE_TOTAL;
+	
+	private AtomicInteger cacheHit = new AtomicInteger();
+	private AtomicInteger totalRequests = new AtomicInteger();
+	
+	private BufferManager bufferManager;
+	
+	public SessionAwareCache(){
+		this(DEFAULT_MAX_SIZE_TOTAL);
+	}
+	
+	SessionAwareCache(int maxSize){
+		this(new DefaultCacheFactory(), Cache.Type.RESULTSET, new CacheConfiguration(Policy.LRU, 60, maxSize));
+	}
+	
+	SessionAwareCache (final CacheFactory cacheFactory, final Cache.Type type, final CacheConfiguration config){
+		this.maxSize = config.getMaxEntries();
+		if(this.maxSize < 0){
+			this.maxSize = DEFAULT_MAX_SIZE_TOTAL;
+		}		
+		this.localCache = new DefaultCache<CacheID, T>("local", maxSize, config.getMaxAgeInSeconds()*1000); //$NON-NLS-1$
+		
+		if (type == Cache.Type.PREPAREDPLAN) {
+			this.distributedCache = localCache;
+		}
+		else {
+			this.distributedCache = cacheFactory.get(type, config);
+			if (type == Cache.Type.RESULTSET) {
+				this.tupleBatchCache = cacheFactory.get(Cache.Type.RESULTSET_BATCHES, config);
+			}
+			else {
+				this.tupleBatchCache = this.distributedCache;
+			}
+		}
+	}	
+	
+	public T get(CacheID id){
+
+		this.totalRequests.getAndIncrement();
+		
+		id.setSessionId(id.originalSessionId);
+		T result = localCache.get(id);
+		
+		if (result == null) {
+			id.setSessionId(null);
+			
+			id.setUserName(id.originalUserName);
+			result = distributedCache.get(id);
+			
+			if (result == null) {
+				id.setUserName(null);
+				result = distributedCache.get(id);
+			}
+			
+			if (result != null && result instanceof Cachable) {
+				Cachable c = (Cachable)result;
+				if (!c.restore(this.tupleBatchCache, this.bufferManager)) {
+					result = null;
+				}
+			}
+		}
+		
+		if (result != null) {
+			LogManager.logTrace(LogConstants.CTX_DQP, "Cache hit for", id); //$NON-NLS-1$
+			cacheHit.getAndIncrement();
+		} else {
+			LogManager.logTrace(LogConstants.CTX_DQP, "Cache miss for", id); //$NON-NLS-1$
+		}
+		return result;
+	}
+	
+	public int getCacheHitCount() {
+		return cacheHit.get();
+	}
+		
+	public int getRequestCount() {
+		return this.totalRequests.get();
+	}
+	
+	public int getTotalCacheEntries() {
+		if (this.localCache == this.distributedCache) {
+			return this.localCache.size();
+		}
+		return localCache.size() + distributedCache.size();
+	}
+	
+	public void put(CacheID id, int determinismLevel, T t, Long ttl){
+		if (determinismLevel >= FunctionMethod.SESSION_DETERMINISTIC) {
+			id.setSessionId(id.originalSessionId);
+			LogManager.logTrace(LogConstants.CTX_DQP, "Adding to session/local cache", id); //$NON-NLS-1$
+			this.localCache.put(id, t, ttl);
+		} 
+		else {
+			
+			boolean insert = true;
+			
+			id.setSessionId(null);
+			
+			if (determinismLevel == FunctionMethod.USER_DETERMINISTIC) {
+				id.setUserName(id.originalUserName);
+			}
+			else {
+				id.setUserName(null);
+			}
+			
+			if (t instanceof Cachable) {
+				Cachable c = (Cachable)t;
+				insert = c.prepare(this.tupleBatchCache, this.bufferManager);
+			}
+			
+			if (insert) {
+				LogManager.logTrace(LogConstants.CTX_DQP, "Adding to global/distributed cache", id); //$NON-NLS-1$
+				this.distributedCache.put(id, t, ttl);
+			}
+		}
+	}
+	
+	/**
+	 * Clear all the cached plans for all the clientConns
+	 * @param clientConn ClientConnection
+	 */
+	public void clearAll(){
+		this.localCache.clear();
+		this.distributedCache.clear();
+		this.totalRequests.set(0);
+		this.cacheHit.set(0);		
+	}	
+	
+	public void clearForVDB(String vdbName, int version) {
+		clearCache(this.localCache, vdbName, version);
+		clearCache(this.distributedCache, vdbName, version);
+	}
+	
+	private void clearCache(Cache<CacheID, T> cache, String vdbName, int version) {
+		Set<CacheID> keys = cache.keys();
+		VDBKey vdbKey = new VDBKey(vdbName, version);
+		for (CacheID key:keys) {
+			if (key.vdbInfo.equals(vdbKey)) {
+				cache.remove(key);
+			}
+		}
+	}
+	
+	public static class CacheID implements Serializable {
+		private static final long serialVersionUID = 8261905111156764744L;
+		private String sql;
+		private VDBKey vdbInfo;
+		private ParseInfo pi;
+		private String sessionId;
+		private String originalSessionId;
+		private List<Serializable> parameters;
+		private String userName;
+		private String originalUserName;
+		
+		public CacheID(DQPWorkContext context, ParseInfo pi, String sql){
+			this(pi, sql, context.getVdbName(), context.getVdbVersion(), context.getSessionId(), context.getUserName());
+		}
+		
+		public CacheID(ParseInfo pi, String sql, String vdbName, int vdbVersion, String sessionId, String userName){
+			this.sql = sql;
+			this.vdbInfo = new VDBKey(vdbName, vdbVersion);
+			this.pi = pi;
+			this.originalSessionId = sessionId;
+			this.originalUserName = userName;
+		}
+
+		
+		public String getSessionId() {
+			return sessionId;
+		}
+		
+		public String getUserName() {
+			return userName;
+		}
+		
+		private void setSessionId(String sessionId) {
+			this.sessionId = sessionId;
+		}
+		
+		/**
+		 * Set the raw (non-Constant) parameter values.
+		 * @param parameters
+		 * @return
+		 */
+		public boolean setParameters(List<?> parameters) {
+			if (parameters !=  null && !parameters.isEmpty()) {
+				this.parameters = new ArrayList<Serializable>();
+				for (Object obj:parameters) {
+					if (obj == null) {
+						this.parameters.add(null);
+						continue;
+					}
+					if (!(obj instanceof Serializable)) {
+						return false;
+					}
+					
+					Class<?> type = DataTypeManager.determineDataTypeClass(obj);
+					if (DataTypeManager.isLOB(type) || type == DataTypeManager.DefaultDataClasses.OBJECT) {
+						return false;
+					}
+					this.parameters.add((Serializable)obj);
+				}
+			}
+			return true;
+		}
+		
+		public String getSql() {
+			return sql;
+		}
+		
+		void setUserName(String name) {
+			this.userName = name;
+		}
+						
+		public boolean equals(Object obj){
+	        if(obj == this) {
+	            return true;
+	        } 
+	        if(! (obj instanceof CacheID)) {
+	            return false;
+	        } 
+        	CacheID that = (CacheID)obj;
+            return EquivalenceUtil.areEqual(this.pi, that.pi) && this.vdbInfo.equals(that.vdbInfo) && this.sql.equals(that.sql) 
+            	&& EquivalenceUtil.areEqual(this.userName, that.userName)            	
+            	&& EquivalenceUtil.areEqual(this.sessionId, that.sessionId)
+            	&& EquivalenceUtil.areEqual(this.parameters, that.parameters);
+		}
+		
+	    public int hashCode() {
+	        return HashCodeUtil.hashCode(0, vdbInfo, sql, pi, this.userName, sessionId, parameters);
+	    }
+	    
+	    @Override
+	    public String toString() {
+	    	return "Cache Entry<" + originalSessionId + "="+ originalUserName + "> params:" + parameters + " sql:" + sql; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	    }
+	    
+	}
+	
+    int getSpaceAllowed() {
+        return maxSize;
+    }
+    
+    public void setBufferManager(BufferManager bufferManager) {
+    	this.bufferManager = bufferManager;
+    }
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,591 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.optimizer.relational.rules;
-
-import java.util.Arrays;
-import java.util.Collection;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.function.metadata.FunctionMethod;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.SupportConstants;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.AccessNode;
-import org.teiid.query.processor.relational.RelationalNode;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.lang.AbstractCompareCriteria;
-import org.teiid.query.sql.lang.AbstractSetCriteria;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.NotCriteria;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.navigator.PreOrderNavigator;
-import org.teiid.query.sql.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.CaseExpression;
-import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.QueryString;
-import org.teiid.query.sql.symbol.ScalarSubquery;
-import org.teiid.query.sql.symbol.SearchedCaseExpression;
-import org.teiid.query.sql.symbol.TextLine;
-import org.teiid.query.sql.symbol.XMLAttributes;
-import org.teiid.query.sql.symbol.XMLElement;
-import org.teiid.query.sql.symbol.XMLForest;
-import org.teiid.query.sql.symbol.XMLNamespaces;
-import org.teiid.query.sql.symbol.XMLParse;
-import org.teiid.query.sql.symbol.XMLQuery;
-import org.teiid.query.sql.symbol.XMLSerialize;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.EvaluatableVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-
-
-/**
- */
-public class CriteriaCapabilityValidatorVisitor extends LanguageVisitor {
-
-    // Initialization state
-    private Object modelID;
-    private QueryMetadataInterface metadata;
-    private CapabilitiesFinder capFinder;
-    private AnalysisRecord analysisRecord;
-
-    // Retrieved during initialization and cached
-    private SourceCapabilities caps;
-    
-    // Output state
-    private TeiidComponentException exception;
-    private boolean valid = true;
-
-    /**
-     * @param iterator
-     * @throws TeiidComponentException 
-     * @throws QueryMetadataException 
-     */
-    CriteriaCapabilityValidatorVisitor(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, SourceCapabilities caps) throws QueryMetadataException, TeiidComponentException {        
-        this.modelID = modelID;
-        this.metadata = metadata;
-        this.capFinder = capFinder;
-        this.caps = caps;
-    }
-    
-    @Override
-    public void visit(XMLAttributes obj) {
-    	markInvalid(obj, "Pushdown of XMLAttributes not allowed"); //$NON-NLS-1$
-    }
-    
-    @Override
-    public void visit(XMLNamespaces obj) {
-    	markInvalid(obj, "Pushdown of XMLNamespaces not allowed"); //$NON-NLS-1$
-    }
-    
-    @Override
-    public void visit(TextLine obj) {
-    	markInvalid(obj, "Pushdown of TextLine not allowed"); //$NON-NLS-1$
-    }
-    
-    @Override
-    public void visit(XMLForest obj) {
-    	markInvalid(obj, "Pushdown of XMLForest not allowed"); //$NON-NLS-1$
-    }
-    
-    @Override
-    public void visit(XMLElement obj) {
-    	markInvalid(obj, "Pushdown of XMLElement not allowed"); //$NON-NLS-1$
-    }
-    
-    @Override
-    public void visit(XMLSerialize obj) {
-    	markInvalid(obj, "Pushdown of XMLSerialize not allowed"); //$NON-NLS-1$
-    }
-    
-    @Override
-    public void visit(XMLParse obj) {
-    	markInvalid(obj, "Pushdown of XMLParse not allowed"); //$NON-NLS-1$
-    }
-    
-    @Override
-    public void visit(XMLQuery obj) {
-    	markInvalid(obj, "Pushdown of XMLQuery not allowed"); //$NON-NLS-1$
-    }
-    
-    @Override
-    public void visit(QueryString obj) {
-    	markInvalid(obj, "Pushdown of QueryString not allowed"); //$NON-NLS-1$
-    }
-    
-    public void visit(AggregateSymbol obj) {
-        try {
-            if(! CapabilitiesUtil.supportsAggregateFunction(modelID, obj, metadata, capFinder)) {
-                markInvalid(obj, "Aggregate function pushdown not supported by source"); //$NON-NLS-1$
-            }         
-        } catch(QueryMetadataException e) {
-            handleException(new TeiidComponentException(e));
-        } catch(TeiidComponentException e) {
-            handleException(e);            
-        }
-    }
-    
-    public void visit(CaseExpression obj) {
-        if(! this.caps.supportsCapability(Capability.QUERY_CASE)) {
-            markInvalid(obj, "CaseExpression pushdown not supported by source"); //$NON-NLS-1$
-        }
-    }
-    
-    public void visit(CompareCriteria obj) {
-    	checkCompareCriteria(obj);
-    }
-    
-    public void checkCompareCriteria(AbstractCompareCriteria obj) {
-        boolean negated = false;
-        // Check if operation is allowed
-        Capability operatorCap = null;
-        switch(obj.getOperator()) {
-            case CompareCriteria.NE: 
-                negated = true;
-            case CompareCriteria.EQ: 
-                operatorCap = Capability.CRITERIA_COMPARE_EQ;
-                break; 
-            case CompareCriteria.LT: 
-            case CompareCriteria.GT: 
-                negated = true;
-            case CompareCriteria.LE: 
-            case CompareCriteria.GE: 
-                operatorCap = Capability.CRITERIA_COMPARE_ORDERED;
-                break;                        
-        }
-
-        // Check if compares are allowed
-        if(! this.caps.supportsCapability(operatorCap)) {
-            markInvalid(obj, "ordered CompareCriteria not supported by source"); //$NON-NLS-1$
-            return;
-        }                       
-        if (negated && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
-        	markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
-        	return;
-        }
-        
-        // Check capabilities of the elements
-        try {
-            checkElementsAreSearchable(obj, SupportConstants.Element.SEARCHABLE_COMPARE);                                
-        } catch(QueryMetadataException e) {
-            handleException(new TeiidComponentException(e));
-        } catch(TeiidComponentException e) {
-            handleException(e);            
-        }
-    }
-
-    public void visit(CompoundCriteria crit) {
-        int operator = crit.getOperator();
-        
-        // Verify capabilities are supported
-        if(operator == CompoundCriteria.OR && !this.caps.supportsCapability(Capability.CRITERIA_OR)) {
-                markInvalid(crit, "OR criteria not supported by source"); //$NON-NLS-1$
-        }
-    }
-
-    public void visit(Function obj) {
-        try {
-            //if the function can be evaluated then return as it will get replaced during the final rewrite 
-            if (EvaluatableVisitor.willBecomeConstant(obj, true)) { 
-                return; 
-            }
-            if(obj.getFunctionDescriptor().getPushdown() == FunctionMethod.CANNOT_PUSHDOWN) {
-            	markInvalid(obj, "Function metadata indicates it cannot be pusheddown."); //$NON-NLS-1$
-            	return;
-            }
-            if (! CapabilitiesUtil.supportsScalarFunction(modelID, obj, metadata, capFinder)) {
-                markInvalid(obj, (obj.isImplicit()?"(implicit) convert":"") + " Function not supported by source"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            }
-        } catch(QueryMetadataException e) {
-            handleException(new TeiidComponentException(e));
-        } catch(TeiidComponentException e) {
-            handleException(e);            
-        }
-    }
-
-    public void visit(IsNullCriteria obj) {
-        // Check if compares are allowed
-        if(! this.caps.supportsCapability(Capability.CRITERIA_ISNULL)) {
-            markInvalid(obj, "IsNull not supported by source"); //$NON-NLS-1$
-            return;
-        }
-        
-        if (obj.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
-        	markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
-            return;
-        }        
-    }
-
-    public void visit(MatchCriteria obj) {
-        // Check if compares are allowed
-        if(! this.caps.supportsCapability(Capability.CRITERIA_LIKE)) {
-            markInvalid(obj, "Like is not supported by source"); //$NON-NLS-1$
-            return;
-        }
-        
-        // Check ESCAPE char if necessary
-        if(obj.getEscapeChar() != MatchCriteria.NULL_ESCAPE_CHAR) {
-            if(! this.caps.supportsCapability(Capability.CRITERIA_LIKE_ESCAPE)) {
-                markInvalid(obj, "Like escape is not supported by source"); //$NON-NLS-1$
-                return;
-            }                
-        }
-        
-        //check NOT
-        if(obj.isNegated() && ! this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
-        	markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
-        	return;
-        }
-
-        // Check capabilities of the elements
-        try {
-            checkElementsAreSearchable(obj, SupportConstants.Element.SEARCHABLE_LIKE);
-        } catch(QueryMetadataException e) {
-            handleException(new TeiidComponentException(e));
-        } catch(TeiidComponentException e) {
-            handleException(e);            
-        }
-    }
-
-    public void visit(NotCriteria obj) {
-        // Check if compares are allowed
-        if(! this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
-            markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
-            return;
-        }
-    }
-
-    public void visit(SearchedCaseExpression obj) {
-        if(! this.caps.supportsCapability(Capability.QUERY_SEARCHED_CASE)) {
-            markInvalid(obj, "SearchedCase is not supported by source"); //$NON-NLS-1$
-        }
-    }
-    
-    public void visit(SetCriteria crit) {
-    	checkAbstractSetCriteria(crit);
-        try {    
-            int maxSize = CapabilitiesUtil.getMaxInCriteriaSize(modelID, metadata, capFinder); 
-            
-            if (maxSize > 0 && crit.getValues().size() > maxSize) {
-                markInvalid(crit, "SetCriteria size exceeds maximum for source"); //$NON-NLS-1$
-                return;
-            }
-        } catch(QueryMetadataException e) {
-            handleException(new TeiidComponentException(e));
-        } catch(TeiidComponentException e) {
-            handleException(e);            
-        }
-    }
-
-    /**
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.ExistsCriteria)
-     */
-    public void visit(ExistsCriteria crit) {
-        // Check if exists criteria are allowed
-        if(! this.caps.supportsCapability(Capability.CRITERIA_EXISTS)) {
-            markInvalid(crit, "Exists is not supported by source"); //$NON-NLS-1$
-            return;
-        }
-        
-        try {
-			if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
-				markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
-			}
-		} catch (TeiidComponentException e) {
-			handleException(e);
-		}
-    }
-
-    /**
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SubqueryCompareCriteria)
-     */
-    public void visit(SubqueryCompareCriteria crit) {
-        // Check if quantification operator is allowed
-        Capability capability = Capability.QUERY_SUBQUERIES_SCALAR;
-        switch(crit.getPredicateQuantifier()) {
-            case SubqueryCompareCriteria.ALL:
-                capability = Capability.CRITERIA_QUANTIFIED_ALL;
-                break;
-            case SubqueryCompareCriteria.ANY:
-                capability = Capability.CRITERIA_QUANTIFIED_SOME;
-                break;
-            case SubqueryCompareCriteria.SOME:
-                capability = Capability.CRITERIA_QUANTIFIED_SOME;
-                break;
-        }
-        if(! this.caps.supportsCapability(capability)) {
-            markInvalid(crit, "SubqueryCompare not supported by source"); //$NON-NLS-1$
-            return;
-        }
-        
-        checkCompareCriteria(crit);
-        
-        // Check capabilities of the elements
-        try {
-            if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
-            	markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
-            }
-        } catch(QueryMetadataException e) {
-            handleException(new TeiidComponentException(e));
-        } catch(TeiidComponentException e) {
-            handleException(e);            
-        }
-    }
-    
-    @Override
-    public void visit(ScalarSubquery obj) {
-    	try {    
-            if(!this.caps.supportsCapability(Capability.QUERY_SUBQUERIES_SCALAR) 
-            		|| validateSubqueryPushdown(obj, modelID, metadata, capFinder, analysisRecord) == null) {
-            	if (obj.getCommand().getCorrelatedReferences() == null) {
-            		obj.setShouldEvaluate(true);
-            	} else {
-            		markInvalid(obj.getCommand(), !this.caps.supportsCapability(Capability.QUERY_SUBQUERIES_SCALAR)?
-            				"Correlated ScalarSubquery is not supported":"Subquery cannot be pushed down"); //$NON-NLS-1$ //$NON-NLS-2$
-            	}
-            }
-        } catch(QueryMetadataException e) {
-            handleException(new TeiidComponentException(e));
-        } catch(TeiidComponentException e) {
-            handleException(e);            
-        }
-    }
-
-    public void visit(SubquerySetCriteria crit) {
-    	checkAbstractSetCriteria(crit);
-        try {    
-            // Check if compares with subqueries are allowed
-            if(! this.caps.supportsCapability(Capability.CRITERIA_IN_SUBQUERY)) {
-                markInvalid(crit, "SubqueryIn is not supported by source"); //$NON-NLS-1$
-                return;
-            }
-
-            if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
-            	markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
-            }
-        } catch(QueryMetadataException e) {
-            handleException(new TeiidComponentException(e));
-        } catch(TeiidComponentException e) {
-            handleException(e);            
-        }
-    }
-    
-    public void checkAbstractSetCriteria(AbstractSetCriteria crit) {
-        try {    
-            // Check if compares are allowed
-            if(! this.caps.supportsCapability(Capability.CRITERIA_IN)) {
-                markInvalid(crit, "In is not supported by source"); //$NON-NLS-1$
-                return;
-            }
-            
-            if (crit.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
-            	markInvalid(crit, "Negation is not supported by source"); //$NON-NLS-1$
-                return;
-            }
-            // Check capabilities of the elements
-            checkElementsAreSearchable(crit, SupportConstants.Element.SEARCHABLE_COMPARE);                        
-                 
-        } catch(QueryMetadataException e) {
-            handleException(new TeiidComponentException(e));
-        } catch(TeiidComponentException e) {
-            handleException(e);            
-        }
-
-    }
-
-    public void visit(DependentSetCriteria crit) {
-    	checkAbstractSetCriteria(crit);
-    }
-
-    private void checkElementsAreSearchable(LanguageObject crit, int searchableType)
-    throws QueryMetadataException, TeiidComponentException {
-    	if (!CapabilitiesUtil.checkElementsAreSearchable(Arrays.asList(crit), metadata, searchableType)) {
-    		markInvalid(crit, "not all source columns support search type"); //$NON-NLS-1$
-    	}
-    }
-    
-    /**
-     * Return null if the subquery cannot be pushed down, otherwise the model
-     * id of the pushdown target.
-     * @param subqueryContainer
-     * @param critNodeModelID
-     * @param metadata
-     * @param capFinder
-     * @return
-     * @throws TeiidComponentException
-     */
-    public static Object validateSubqueryPushdown(SubqueryContainer subqueryContainer, Object critNodeModelID, 
-    		QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord) throws TeiidComponentException {
-    	ProcessorPlan plan = subqueryContainer.getCommand().getProcessorPlan();
-    	if (plan != null) {
-    		QueryCommand queryCommand = getQueryCommand(plan);
-    		
-    		if (queryCommand == null) {
-    			return null;
-    		}
-    		
-    		critNodeModelID = validateCommandPushdown(critNodeModelID, metadata, capFinder,	queryCommand);  
-    	}
-    	if (critNodeModelID == null) {
-    		return null;
-    	}
-        // Check whether source supports correlated subqueries and if not, whether criteria has them
-        SymbolMap refs = subqueryContainer.getCommand().getCorrelatedReferences();
-        try {
-            if(refs != null && !refs.asMap().isEmpty()) {
-                if(! CapabilitiesUtil.supports(Capability.QUERY_SUBQUERIES_CORRELATED, critNodeModelID, metadata, capFinder)) {
-                    return null;
-                }
-                //TODO: this check sees as correlated references as coming from the containing scope
-                //but this is only an issue with deeply nested subqueries
-                if (!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(subqueryContainer.getCommand(), critNodeModelID, metadata, capFinder, analysisRecord )) {
-                    return null;
-                }
-            }
-        } catch(QueryMetadataException e) {
-            throw new TeiidComponentException(e);                  
-        }
-
-        // Found no reason why this node is not eligible
-        return critNodeModelID;
-    }
-
-	public static Object validateCommandPushdown(Object critNodeModelID,
-			QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
-			QueryCommand queryCommand) throws TeiidComponentException {
-		// Check that query in access node is for the same model as current node
-		try {                
-		    Collection subQueryGroups = GroupCollectorVisitor.getGroupsIgnoreInlineViews(queryCommand, false);
-		    if(subQueryGroups.size() == 0) {
-		        // No FROM?
-		        return null;
-		    }
-		    GroupSymbol subQueryGroup = (GroupSymbol)subQueryGroups.iterator().next();
-
-		    Object modelID = subQueryGroup.getModelMetadataId();
-		    if (modelID == null) {
-		    	modelID = metadata.getModelID(subQueryGroup.getMetadataID());
-		    }
-		    if (critNodeModelID == null) {
-		    	critNodeModelID = modelID;
-		    } else if(!CapabilitiesUtil.isSameConnector(critNodeModelID, modelID, metadata, capFinder)) {
-		        return null;
-		    }
-		} catch(QueryMetadataException e) {
-		    throw new TeiidComponentException(e, QueryPlugin.Util.getString("RulePushSelectCriteria.Error_getting_modelID")); //$NON-NLS-1$
-		}
-		return critNodeModelID;
-	}
-
-	public static QueryCommand getQueryCommand(ProcessorPlan plan) {
-		if(!(plan instanceof RelationalPlan)) {
-		    return null;
-		}
-		            
-		RelationalPlan rplan = (RelationalPlan) plan;
-		
-		// Check that the plan is just an access node                
-		RelationalNode accessNode = rplan.getRootNode();
-		if(accessNode == null || ! (accessNode instanceof AccessNode) || accessNode.getChildren()[0] != null) {
-		    return null;
-		}
-		
-		// Check that command in access node is a query
-		Command command = ((AccessNode)accessNode).getCommand();
-		if(command == null || !(command instanceof QueryCommand) || ((command instanceof Query) && ((Query)command).getIsXML())) {
-		    return null;
-		}
-		
-		QueryCommand queryCommand = (QueryCommand)command;
-		return queryCommand;
-	}
-        
-    private void handleException(TeiidComponentException e) {
-        this.valid = false;
-        this.exception = e;
-        setAbort(true);
-    }
-    
-    public TeiidComponentException getException() {
-        return this.exception;
-    }
-    
-    private void markInvalid(LanguageObject object, String reason) {
-        this.valid = false;
-        setAbort(true);
-        if (analysisRecord != null && analysisRecord.recordDebug()) {
-        	analysisRecord.println(reason + " " + object); //$NON-NLS-1$
-        }
-    }
-    
-    public boolean isValid() {
-        return this.valid;
-    }
-
-    public static boolean canPushLanguageObject(LanguageObject obj, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord) throws QueryMetadataException, TeiidComponentException {
-        if(obj == null) {
-            return true;
-        }
-        
-        if(modelID == null || metadata.isVirtualModel(modelID)) {
-            // Couldn't determine model ID, so give up
-            return false;
-        } 
-        
-        String modelName = metadata.getFullName(modelID);
-        SourceCapabilities caps = capFinder.findCapabilities(modelName);
-
-        if (caps == null) {
-        	return true; //this doesn't seem right, but tests were expecting it...
-        }
-        
-        CriteriaCapabilityValidatorVisitor visitor = new CriteriaCapabilityValidatorVisitor(modelID, metadata, capFinder, caps);
-        PreOrderNavigator.doVisit(obj, visitor);
-        
-        if(visitor.getException() != null) {
-            throw visitor.getException();
-        } 
-
-        return visitor.isValid();
-    }
-
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,591 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.optimizer.relational.rules;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.function.metadata.FunctionMethod;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.SupportConstants;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.AccessNode;
+import org.teiid.query.processor.relational.RelationalNode;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.lang.AbstractCompareCriteria;
+import org.teiid.query.sql.lang.AbstractSetCriteria;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.NotCriteria;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.navigator.PreOrderNavigator;
+import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.CaseExpression;
+import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.QueryString;
+import org.teiid.query.sql.symbol.ScalarSubquery;
+import org.teiid.query.sql.symbol.SearchedCaseExpression;
+import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.XMLAttributes;
+import org.teiid.query.sql.symbol.XMLElement;
+import org.teiid.query.sql.symbol.XMLForest;
+import org.teiid.query.sql.symbol.XMLNamespaces;
+import org.teiid.query.sql.symbol.XMLParse;
+import org.teiid.query.sql.symbol.XMLQuery;
+import org.teiid.query.sql.symbol.XMLSerialize;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.EvaluatableVisitor;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+
+
+/**
+ */
+public class CriteriaCapabilityValidatorVisitor extends LanguageVisitor {
+
+    // Initialization state
+    private Object modelID;
+    private QueryMetadataInterface metadata;
+    private CapabilitiesFinder capFinder;
+    private AnalysisRecord analysisRecord;
+
+    // Retrieved during initialization and cached
+    private SourceCapabilities caps;
+    
+    // Output state
+    private TeiidComponentException exception;
+    private boolean valid = true;
+
+    /**
+     * @param iterator
+     * @throws TeiidComponentException 
+     * @throws QueryMetadataException 
+     */
+    CriteriaCapabilityValidatorVisitor(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, SourceCapabilities caps) throws QueryMetadataException, TeiidComponentException {        
+        this.modelID = modelID;
+        this.metadata = metadata;
+        this.capFinder = capFinder;
+        this.caps = caps;
+    }
+    
+    @Override
+    public void visit(XMLAttributes obj) {
+    	markInvalid(obj, "Pushdown of XMLAttributes not allowed"); //$NON-NLS-1$
+    }
+    
+    @Override
+    public void visit(XMLNamespaces obj) {
+    	markInvalid(obj, "Pushdown of XMLNamespaces not allowed"); //$NON-NLS-1$
+    }
+    
+    @Override
+    public void visit(TextLine obj) {
+    	markInvalid(obj, "Pushdown of TextLine not allowed"); //$NON-NLS-1$
+    }
+    
+    @Override
+    public void visit(XMLForest obj) {
+    	markInvalid(obj, "Pushdown of XMLForest not allowed"); //$NON-NLS-1$
+    }
+    
+    @Override
+    public void visit(XMLElement obj) {
+    	markInvalid(obj, "Pushdown of XMLElement not allowed"); //$NON-NLS-1$
+    }
+    
+    @Override
+    public void visit(XMLSerialize obj) {
+    	markInvalid(obj, "Pushdown of XMLSerialize not allowed"); //$NON-NLS-1$
+    }
+    
+    @Override
+    public void visit(XMLParse obj) {
+    	markInvalid(obj, "Pushdown of XMLParse not allowed"); //$NON-NLS-1$
+    }
+    
+    @Override
+    public void visit(XMLQuery obj) {
+    	markInvalid(obj, "Pushdown of XMLQuery not allowed"); //$NON-NLS-1$
+    }
+    
+    @Override
+    public void visit(QueryString obj) {
+    	markInvalid(obj, "Pushdown of QueryString not allowed"); //$NON-NLS-1$
+    }
+    
+    public void visit(AggregateSymbol obj) {
+        try {
+            if(! CapabilitiesUtil.supportsAggregateFunction(modelID, obj, metadata, capFinder)) {
+                markInvalid(obj, "Aggregate function pushdown not supported by source"); //$NON-NLS-1$
+            }         
+        } catch(QueryMetadataException e) {
+            handleException(new TeiidComponentException(e));
+        } catch(TeiidComponentException e) {
+            handleException(e);            
+        }
+    }
+    
+    public void visit(CaseExpression obj) {
+        if(! this.caps.supportsCapability(Capability.QUERY_CASE)) {
+            markInvalid(obj, "CaseExpression pushdown not supported by source"); //$NON-NLS-1$
+        }
+    }
+    
+    public void visit(CompareCriteria obj) {
+    	checkCompareCriteria(obj);
+    }
+    
+    public void checkCompareCriteria(AbstractCompareCriteria obj) {
+        boolean negated = false;
+        // Check if operation is allowed
+        Capability operatorCap = null;
+        switch(obj.getOperator()) {
+            case CompareCriteria.NE: 
+                negated = true;
+            case CompareCriteria.EQ: 
+                operatorCap = Capability.CRITERIA_COMPARE_EQ;
+                break; 
+            case CompareCriteria.LT: 
+            case CompareCriteria.GT: 
+                negated = true;
+            case CompareCriteria.LE: 
+            case CompareCriteria.GE: 
+                operatorCap = Capability.CRITERIA_COMPARE_ORDERED;
+                break;                        
+        }
+
+        // Check if compares are allowed
+        if(! this.caps.supportsCapability(operatorCap)) {
+            markInvalid(obj, "ordered CompareCriteria not supported by source"); //$NON-NLS-1$
+            return;
+        }                       
+        if (negated && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+        	markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
+        	return;
+        }
+        
+        // Check capabilities of the elements
+        try {
+            checkElementsAreSearchable(obj, SupportConstants.Element.SEARCHABLE_COMPARE);                                
+        } catch(QueryMetadataException e) {
+            handleException(new TeiidComponentException(e));
+        } catch(TeiidComponentException e) {
+            handleException(e);            
+        }
+    }
+
+    public void visit(CompoundCriteria crit) {
+        int operator = crit.getOperator();
+        
+        // Verify capabilities are supported
+        if(operator == CompoundCriteria.OR && !this.caps.supportsCapability(Capability.CRITERIA_OR)) {
+                markInvalid(crit, "OR criteria not supported by source"); //$NON-NLS-1$
+        }
+    }
+
+    public void visit(Function obj) {
+        try {
+            //if the function can be evaluated then return as it will get replaced during the final rewrite 
+            if (EvaluatableVisitor.willBecomeConstant(obj, true)) { 
+                return; 
+            }
+            if(obj.getFunctionDescriptor().getPushdown() == FunctionMethod.CANNOT_PUSHDOWN) {
+            	markInvalid(obj, "Function metadata indicates it cannot be pusheddown."); //$NON-NLS-1$
+            	return;
+            }
+            if (! CapabilitiesUtil.supportsScalarFunction(modelID, obj, metadata, capFinder)) {
+                markInvalid(obj, (obj.isImplicit()?"(implicit) ":"") + obj.getName() + " function not supported by source"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            }
+        } catch(QueryMetadataException e) {
+            handleException(new TeiidComponentException(e));
+        } catch(TeiidComponentException e) {
+            handleException(e);            
+        }
+    }
+
+    public void visit(IsNullCriteria obj) {
+        // Check if compares are allowed
+        if(! this.caps.supportsCapability(Capability.CRITERIA_ISNULL)) {
+            markInvalid(obj, "IsNull not supported by source"); //$NON-NLS-1$
+            return;
+        }
+        
+        if (obj.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+        	markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
+            return;
+        }        
+    }
+
+    public void visit(MatchCriteria obj) {
+        // Check if compares are allowed
+        if(! this.caps.supportsCapability(Capability.CRITERIA_LIKE)) {
+            markInvalid(obj, "Like is not supported by source"); //$NON-NLS-1$
+            return;
+        }
+        
+        // Check ESCAPE char if necessary
+        if(obj.getEscapeChar() != MatchCriteria.NULL_ESCAPE_CHAR) {
+            if(! this.caps.supportsCapability(Capability.CRITERIA_LIKE_ESCAPE)) {
+                markInvalid(obj, "Like escape is not supported by source"); //$NON-NLS-1$
+                return;
+            }                
+        }
+        
+        //check NOT
+        if(obj.isNegated() && ! this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+        	markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
+        	return;
+        }
+
+        // Check capabilities of the elements
+        try {
+            checkElementsAreSearchable(obj, SupportConstants.Element.SEARCHABLE_LIKE);
+        } catch(QueryMetadataException e) {
+            handleException(new TeiidComponentException(e));
+        } catch(TeiidComponentException e) {
+            handleException(e);            
+        }
+    }
+
+    public void visit(NotCriteria obj) {
+        // Check if compares are allowed
+        if(! this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+            markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
+            return;
+        }
+    }
+
+    public void visit(SearchedCaseExpression obj) {
+        if(! this.caps.supportsCapability(Capability.QUERY_SEARCHED_CASE)) {
+            markInvalid(obj, "SearchedCase is not supported by source"); //$NON-NLS-1$
+        }
+    }
+    
+    public void visit(SetCriteria crit) {
+    	checkAbstractSetCriteria(crit);
+        try {    
+            int maxSize = CapabilitiesUtil.getMaxInCriteriaSize(modelID, metadata, capFinder); 
+            
+            if (maxSize > 0 && crit.getValues().size() > maxSize) {
+                markInvalid(crit, "SetCriteria size exceeds maximum for source"); //$NON-NLS-1$
+                return;
+            }
+        } catch(QueryMetadataException e) {
+            handleException(new TeiidComponentException(e));
+        } catch(TeiidComponentException e) {
+            handleException(e);            
+        }
+    }
+
+    /**
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.ExistsCriteria)
+     */
+    public void visit(ExistsCriteria crit) {
+        // Check if exists criteria are allowed
+        if(! this.caps.supportsCapability(Capability.CRITERIA_EXISTS)) {
+            markInvalid(crit, "Exists is not supported by source"); //$NON-NLS-1$
+            return;
+        }
+        
+        try {
+			if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
+				markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
+			}
+		} catch (TeiidComponentException e) {
+			handleException(e);
+		}
+    }
+
+    /**
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SubqueryCompareCriteria)
+     */
+    public void visit(SubqueryCompareCriteria crit) {
+        // Check if quantification operator is allowed
+        Capability capability = Capability.QUERY_SUBQUERIES_SCALAR;
+        switch(crit.getPredicateQuantifier()) {
+            case SubqueryCompareCriteria.ALL:
+                capability = Capability.CRITERIA_QUANTIFIED_ALL;
+                break;
+            case SubqueryCompareCriteria.ANY:
+                capability = Capability.CRITERIA_QUANTIFIED_SOME;
+                break;
+            case SubqueryCompareCriteria.SOME:
+                capability = Capability.CRITERIA_QUANTIFIED_SOME;
+                break;
+        }
+        if(! this.caps.supportsCapability(capability)) {
+            markInvalid(crit, "SubqueryCompare not supported by source"); //$NON-NLS-1$
+            return;
+        }
+        
+        checkCompareCriteria(crit);
+        
+        // Check capabilities of the elements
+        try {
+            if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
+            	markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
+            }
+        } catch(QueryMetadataException e) {
+            handleException(new TeiidComponentException(e));
+        } catch(TeiidComponentException e) {
+            handleException(e);            
+        }
+    }
+    
+    @Override
+    public void visit(ScalarSubquery obj) {
+    	try {    
+            if(!this.caps.supportsCapability(Capability.QUERY_SUBQUERIES_SCALAR) 
+            		|| validateSubqueryPushdown(obj, modelID, metadata, capFinder, analysisRecord) == null) {
+            	if (obj.getCommand().getCorrelatedReferences() == null) {
+            		obj.setShouldEvaluate(true);
+            	} else {
+            		markInvalid(obj.getCommand(), !this.caps.supportsCapability(Capability.QUERY_SUBQUERIES_SCALAR)?
+            				"Correlated ScalarSubquery is not supported":"Subquery cannot be pushed down"); //$NON-NLS-1$ //$NON-NLS-2$
+            	}
+            }
+        } catch(QueryMetadataException e) {
+            handleException(new TeiidComponentException(e));
+        } catch(TeiidComponentException e) {
+            handleException(e);            
+        }
+    }
+
+    public void visit(SubquerySetCriteria crit) {
+    	checkAbstractSetCriteria(crit);
+        try {    
+            // Check if compares with subqueries are allowed
+            if(! this.caps.supportsCapability(Capability.CRITERIA_IN_SUBQUERY)) {
+                markInvalid(crit, "SubqueryIn is not supported by source"); //$NON-NLS-1$
+                return;
+            }
+
+            if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
+            	markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
+            }
+        } catch(QueryMetadataException e) {
+            handleException(new TeiidComponentException(e));
+        } catch(TeiidComponentException e) {
+            handleException(e);            
+        }
+    }
+    
+    public void checkAbstractSetCriteria(AbstractSetCriteria crit) {
+        try {    
+            // Check if compares are allowed
+            if(! this.caps.supportsCapability(Capability.CRITERIA_IN)) {
+                markInvalid(crit, "In is not supported by source"); //$NON-NLS-1$
+                return;
+            }
+            
+            if (crit.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+            	markInvalid(crit, "Negation is not supported by source"); //$NON-NLS-1$
+                return;
+            }
+            // Check capabilities of the elements
+            checkElementsAreSearchable(crit, SupportConstants.Element.SEARCHABLE_COMPARE);                        
+                 
+        } catch(QueryMetadataException e) {
+            handleException(new TeiidComponentException(e));
+        } catch(TeiidComponentException e) {
+            handleException(e);            
+        }
+
+    }
+
+    public void visit(DependentSetCriteria crit) {
+    	checkAbstractSetCriteria(crit);
+    }
+
+    private void checkElementsAreSearchable(LanguageObject crit, int searchableType)
+    throws QueryMetadataException, TeiidComponentException {
+    	if (!CapabilitiesUtil.checkElementsAreSearchable(Arrays.asList(crit), metadata, searchableType)) {
+    		markInvalid(crit, "not all source columns support search type"); //$NON-NLS-1$
+    	}
+    }
+    
+    /**
+     * Return null if the subquery cannot be pushed down, otherwise the model
+     * id of the pushdown target.
+     * @param subqueryContainer
+     * @param critNodeModelID
+     * @param metadata
+     * @param capFinder
+     * @return
+     * @throws TeiidComponentException
+     */
+    public static Object validateSubqueryPushdown(SubqueryContainer subqueryContainer, Object critNodeModelID, 
+    		QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord) throws TeiidComponentException {
+    	ProcessorPlan plan = subqueryContainer.getCommand().getProcessorPlan();
+    	if (plan != null) {
+    		QueryCommand queryCommand = getQueryCommand(plan);
+    		
+    		if (queryCommand == null) {
+    			return null;
+    		}
+    		
+    		critNodeModelID = validateCommandPushdown(critNodeModelID, metadata, capFinder,	queryCommand);  
+    	}
+    	if (critNodeModelID == null) {
+    		return null;
+    	}
+        // Check whether source supports correlated subqueries and if not, whether criteria has them
+        SymbolMap refs = subqueryContainer.getCommand().getCorrelatedReferences();
+        try {
+            if(refs != null && !refs.asMap().isEmpty()) {
+                if(! CapabilitiesUtil.supports(Capability.QUERY_SUBQUERIES_CORRELATED, critNodeModelID, metadata, capFinder)) {
+                    return null;
+                }
+                //TODO: this check sees as correlated references as coming from the containing scope
+                //but this is only an issue with deeply nested subqueries
+                if (!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(subqueryContainer.getCommand(), critNodeModelID, metadata, capFinder, analysisRecord )) {
+                    return null;
+                }
+            }
+        } catch(QueryMetadataException e) {
+            throw new TeiidComponentException(e);                  
+        }
+
+        // Found no reason why this node is not eligible
+        return critNodeModelID;
+    }
+
+	public static Object validateCommandPushdown(Object critNodeModelID,
+			QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
+			QueryCommand queryCommand) throws TeiidComponentException {
+		// Check that query in access node is for the same model as current node
+		try {                
+		    Collection subQueryGroups = GroupCollectorVisitor.getGroupsIgnoreInlineViews(queryCommand, false);
+		    if(subQueryGroups.size() == 0) {
+		        // No FROM?
+		        return null;
+		    }
+		    GroupSymbol subQueryGroup = (GroupSymbol)subQueryGroups.iterator().next();
+
+		    Object modelID = subQueryGroup.getModelMetadataId();
+		    if (modelID == null) {
+		    	modelID = metadata.getModelID(subQueryGroup.getMetadataID());
+		    }
+		    if (critNodeModelID == null) {
+		    	critNodeModelID = modelID;
+		    } else if(!CapabilitiesUtil.isSameConnector(critNodeModelID, modelID, metadata, capFinder)) {
+		        return null;
+		    }
+		} catch(QueryMetadataException e) {
+		    throw new TeiidComponentException(e, QueryPlugin.Util.getString("RulePushSelectCriteria.Error_getting_modelID")); //$NON-NLS-1$
+		}
+		return critNodeModelID;
+	}
+
+	public static QueryCommand getQueryCommand(ProcessorPlan plan) {
+		if(!(plan instanceof RelationalPlan)) {
+		    return null;
+		}
+		            
+		RelationalPlan rplan = (RelationalPlan) plan;
+		
+		// Check that the plan is just an access node                
+		RelationalNode accessNode = rplan.getRootNode();
+		if(accessNode == null || ! (accessNode instanceof AccessNode) || accessNode.getChildren()[0] != null) {
+		    return null;
+		}
+		
+		// Check that command in access node is a query
+		Command command = ((AccessNode)accessNode).getCommand();
+		if(command == null || !(command instanceof QueryCommand) || ((command instanceof Query) && ((Query)command).getIsXML())) {
+		    return null;
+		}
+		
+		QueryCommand queryCommand = (QueryCommand)command;
+		return queryCommand;
+	}
+        
+    private void handleException(TeiidComponentException e) {
+        this.valid = false;
+        this.exception = e;
+        setAbort(true);
+    }
+    
+    public TeiidComponentException getException() {
+        return this.exception;
+    }
+    
+    private void markInvalid(LanguageObject object, String reason) {
+        this.valid = false;
+        setAbort(true);
+        if (analysisRecord != null && analysisRecord.recordDebug()) {
+        	analysisRecord.println(reason + " " + object); //$NON-NLS-1$
+        }
+    }
+    
+    public boolean isValid() {
+        return this.valid;
+    }
+
+    public static boolean canPushLanguageObject(LanguageObject obj, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord) throws QueryMetadataException, TeiidComponentException {
+        if(obj == null) {
+            return true;
+        }
+        
+        if(modelID == null || metadata.isVirtualModel(modelID)) {
+            // Couldn't determine model ID, so give up
+            return false;
+        } 
+        
+        String modelName = metadata.getFullName(modelID);
+        SourceCapabilities caps = capFinder.findCapabilities(modelName);
+
+        if (caps == null) {
+        	return true; //this doesn't seem right, but tests were expecting it...
+        }
+        
+        CriteriaCapabilityValidatorVisitor visitor = new CriteriaCapabilityValidatorVisitor(modelID, metadata, capFinder, caps);
+        PreOrderNavigator.doVisit(obj, visitor);
+        
+        if(visitor.getException() != null) {
+            throw visitor.getException();
+        } 
+
+        return visitor.isValid();
+    }
+
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/JoinRegion.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/query/optimizer/relational/rules/JoinRegion.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/JoinRegion.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,515 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.query.function.metadata.FunctionMethod;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.relational.RelationalPlanner;
-import org.teiid.query.optimizer.relational.plantree.NodeConstants;
-import org.teiid.query.optimizer.relational.plantree.PlanNode;
-import org.teiid.query.resolver.util.AccessPattern;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
-
-
-/**
- *  A join region is a set of cross and inner joins whose ordering is completely interchangeable.
- *  
- *  It can be conceptually thought of as:
- *     Criteria node some combination of groups A, B, C
- *     Criteria node some combination of groups A, B, C
- *     ...
- *     Join
- *       JoinSourceA
- *       JoinSourceB
- *       JoinSourceC
- *  
- *  A full binary join tree is then constructed out of this join region such that all of the
- *  criteria is pushed to its lowest point.
- *  
- */
-class JoinRegion {
-    
-    private PlanNode joinRoot;
-    
-    public static final int UNKNOWN_TUPLE_EST = 100000;
-    
-    private LinkedHashMap<PlanNode, PlanNode> dependentJoinSourceNodes = new LinkedHashMap<PlanNode, PlanNode>();
-    private LinkedHashMap<PlanNode, PlanNode> joinSourceNodes = new LinkedHashMap<PlanNode, PlanNode>();
-        
-    private List<PlanNode> dependentCritieraNodes = new ArrayList<PlanNode>();
-    private List<PlanNode> criteriaNodes = new ArrayList<PlanNode>();
-    
-    private List<Collection<AccessPattern>> unsatisfiedAccessPatterns = new LinkedList<Collection<AccessPattern>>();
-    private boolean containsNestedTable;
-    
-    private Map<ElementSymbol, Set<Collection<GroupSymbol>>> dependentCriteriaElements;
-    private Map<PlanNode, Set<PlanNode>> critieriaToSourceMap;
-    
-    public PlanNode getJoinRoot() {
-        return joinRoot;
-    }
-    
-    public void setContainsNestedTable(boolean containsNestedTable) {
-		this.containsNestedTable = containsNestedTable;
-	}
-    
-    public boolean containsNestedTable() {
-		return containsNestedTable;
-	}
-    
-    public List<Collection<AccessPattern>> getUnsatisfiedAccessPatterns() {
-        return unsatisfiedAccessPatterns;
-    }
-    
-    public Map<PlanNode, PlanNode> getJoinSourceNodes() {
-        return joinSourceNodes;
-    }
-
-    public Map<PlanNode, PlanNode> getDependentJoinSourceNodes() {
-        return dependentJoinSourceNodes;
-    }
-    
-    public List<PlanNode> getCriteriaNodes() {
-        return criteriaNodes;
-    }
-    
-    public List<PlanNode> getDependentCriteriaNodes() {
-        return dependentCritieraNodes;
-    }
-    
-    public Map<ElementSymbol, Set<Collection<GroupSymbol>>> getDependentCriteriaElements() {
-        return this.dependentCriteriaElements;
-    }
-
-    public Map<PlanNode, Set<PlanNode>> getCritieriaToSourceMap() {
-        return this.critieriaToSourceMap;
-    }
-
-    public void addJoinSourceNode(PlanNode sourceNode) {
-        PlanNode root = sourceNode;
-        while (root.getParent() != null && root.getParent().getType() == NodeConstants.Types.SELECT) {
-            root = root.getParent();
-        }
-        if (sourceNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
-            Collection<AccessPattern> aps = (Collection<AccessPattern>)sourceNode.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
-            unsatisfiedAccessPatterns.add(aps);
-            dependentJoinSourceNodes.put(sourceNode, root);
-        } else {
-            joinSourceNodes.put(sourceNode, root);
-        }
-        
-        if (joinRoot == null) {
-            joinRoot = root;
-        }
-    }
-
-    public void addParentCriteria(PlanNode sourceNode) {
-        PlanNode parent = sourceNode.getParent();
-        while (parent != null && parent.getType() == NodeConstants.Types.SELECT) {
-            criteriaNodes.add(parent);
-            sourceNode = parent;
-            parent = parent.getParent();
-        }
-        if (joinRoot == null) {
-            joinRoot = sourceNode;
-        }
-    }
-                    
-    public void addJoinCriteriaList(List<? extends Criteria> joinCriteria) {
-        if (joinCriteria == null || joinCriteria.isEmpty()) {
-            return;
-        }
-        for (Criteria crit : joinCriteria) {
-            criteriaNodes.add(RelationalPlanner.createSelectNode(crit, false));
-        }
-    }
-    
-    /**
-     * This will rebuild the join tree starting at the join root.
-     * 
-     * A left linear tree will be constructed out of the ordering of the 
-     * join sources.
-     * 
-     * Criteria nodes are simply placed at the top of the join region in order
-     * to be pushed by rule PushSelectSriteria.
-     * 
-     */
-    public void reconstructJoinRegoin() {
-        LinkedHashMap<PlanNode, PlanNode> combined = new LinkedHashMap<PlanNode, PlanNode>(joinSourceNodes);
-        combined.putAll(dependentJoinSourceNodes);
-        
-        PlanNode root = null;
-        
-        if (combined.size() < 2) {
-            root = combined.values().iterator().next();
-            root.removeProperty(NodeConstants.Info.EST_CARDINALITY);
-        } else {
-            root = RulePlanJoins.createJoinNode();
-        
-            for (Map.Entry<PlanNode, PlanNode> entry : combined.entrySet()) {
-                PlanNode joinSourceRoot = entry.getValue();
-                joinSourceRoot.removeProperty(NodeConstants.Info.EST_CARDINALITY);
-                if (root.getChildCount() == 2) {
-                    PlanNode parentJoin = RulePlanJoins.createJoinNode();
-                    parentJoin.addFirstChild(root);
-                    parentJoin.addGroups(root.getGroups());
-                    root = parentJoin;
-                }
-                root.addLastChild(joinSourceRoot);
-                root.addGroups(entry.getKey().getGroups());
-            }
-        }
-        LinkedList<PlanNode> criteria = new LinkedList<PlanNode>(dependentCritieraNodes);
-        criteria.addAll(criteriaNodes);
-
-        PlanNode parent = this.joinRoot.getParent();
-        
-        boolean isLeftChild = parent.getFirstChild() == this.joinRoot;
-
-        parent.removeChild(joinRoot);
-        
-        for (PlanNode critNode : criteria) {
-            critNode.removeFromParent();
-            critNode.removeAllChildren();
-            critNode.addFirstChild(root);
-            root = critNode;
-            critNode.removeProperty(NodeConstants.Info.IS_COPIED);
-            critNode.removeProperty(NodeConstants.Info.EST_CARDINALITY);
-        }
-
-        if (isLeftChild) {
-            parent.addFirstChild(root);
-        } else {
-            parent.addLastChild(root);
-        }
-        this.joinRoot = root;
-    }
-    
-    /**
-     * Will provide an estimate of cost by summing the estimated tuples flowing through
-     * each intermediate join. 
-     *  
-     * @param joinOrder
-     * @param metadata
-     * @return
-     * @throws TeiidComponentException 
-     * @throws QueryMetadataException 
-     */
-    public double scoreRegion(Object[] joinOrder, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
-        List<Map.Entry<PlanNode, PlanNode>> joinSourceEntries = new ArrayList<Map.Entry<PlanNode, PlanNode>>(joinSourceNodes.entrySet());
-        double totalIntermediatCost = 0;
-        double cost = 1;
-        
-        HashSet<PlanNode> criteria = new HashSet<PlanNode>(this.criteriaNodes);
-        HashSet<GroupSymbol> groups = new HashSet<GroupSymbol>(this.joinSourceNodes.size());
-        
-        for (int i = 0; i < joinOrder.length; i++) {
-            Integer source = (Integer)joinOrder[i];
-            
-            Map.Entry<PlanNode, PlanNode> entry = joinSourceEntries.get(source.intValue());
-            PlanNode joinSourceRoot = entry.getValue();
-            
-            //check to make sure that this group ordering satisfies the access patterns
-            if (!this.unsatisfiedAccessPatterns.isEmpty() || this.containsNestedTable) {
-                PlanNode joinSource = entry.getKey();
-                
-                Collection<GroupSymbol> requiredGroups = (Collection<GroupSymbol>)joinSource.getProperty(NodeConstants.Info.REQUIRED_ACCESS_PATTERN_GROUPS);
-                
-                if (requiredGroups != null && !groups.containsAll(requiredGroups)) {
-                    return Double.MAX_VALUE;
-                }
-            }
-            
-            groups.addAll(joinSourceRoot.getGroups());
-            
-            float sourceCost = ((Float)joinSourceRoot.getProperty(NodeConstants.Info.EST_CARDINALITY)).floatValue();
-            
-            List<PlanNode> applicableCriteria = null;
-            
-            if (!criteria.isEmpty() && i > 0) {
-                applicableCriteria = getJoinCriteriaForGroups(groups, criteria);
-            }
-            
-        	if (sourceCost == NewCalculateCostUtil.UNKNOWN_VALUE) {
-        		sourceCost = UNKNOWN_TUPLE_EST;
-                if (applicableCriteria != null && !applicableCriteria.isEmpty()) {
-                	CompoundCriteria cc = new CompoundCriteria();
-                	for (PlanNode planNode : applicableCriteria) {
-    					cc.addCriteria((Criteria) planNode.getProperty(NodeConstants.Info.SELECT_CRITERIA));
-    				}
-                	sourceCost = (float)cost;
-                	criteria.removeAll(applicableCriteria);
-	            	applicableCriteria = null;
-            		if (NewCalculateCostUtil.usesKey(cc, metadata)) {
-    	            	sourceCost = Math.min(UNKNOWN_TUPLE_EST, sourceCost * Math.min(NewCalculateCostUtil.UNKNOWN_JOIN_SCALING, sourceCost));
-            		} else {
-    	            	sourceCost = Math.min(UNKNOWN_TUPLE_EST, sourceCost * Math.min(NewCalculateCostUtil.UNKNOWN_JOIN_SCALING * 2, sourceCost));
-            		}
-                }
-            } else if (Double.isInfinite(sourceCost) || Double.isNaN(sourceCost)) {
-            	return Double.MAX_VALUE;
-            }
-        
-            cost *= sourceCost;
-            
-            if (applicableCriteria != null) {
-                for (PlanNode criteriaNode : applicableCriteria) {
-                    float filter = ((Float)criteriaNode.getProperty(NodeConstants.Info.EST_SELECTIVITY)).floatValue();
-                    
-                    cost *= filter;
-                }
-                
-                criteria.removeAll(applicableCriteria);
-            }
-            totalIntermediatCost += cost;
-        }
-        
-        return totalIntermediatCost;
-    }
-    
-    /**
-     *  Returns true if every element in an unsatisfied access pattern can be satisfied by the current join criteria
-     *  This does not necessarily mean that a join tree will be successfully created
-     */
-    public boolean isSatisfiable() {
-    	for (Collection<AccessPattern> accessPatterns : getUnsatisfiedAccessPatterns()) {
-            boolean matchedAll = false;
-            for (AccessPattern ap : accessPatterns) {
-                if (dependentCriteriaElements.keySet().containsAll(ap.getUnsatisfied())) {
-                    matchedAll = true;
-                    break;
-                }
-            }
-            if (!matchedAll) {
-                return false;
-            }
-        }
-        
-        return true;
-    }
-
-    public void initializeCostingInformation(QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
-    	for (PlanNode node : joinSourceNodes.values()) {
-            NewCalculateCostUtil.computeCostForTree(node, metadata);
-        }
-        
-        estimateCriteriaSelectivity(metadata);        
-    }
-
-    /** 
-     * @param metadata
-     * @throws QueryMetadataException
-     * @throws TeiidComponentException
-     */
-    private void estimateCriteriaSelectivity(QueryMetadataInterface metadata) throws QueryMetadataException,
-                                                                             TeiidComponentException {
-        for (PlanNode node : criteriaNodes) {
-            Criteria crit = (Criteria)node.getProperty(NodeConstants.Info.SELECT_CRITERIA);
-            
-            float[] baseCosts = new float[] {100, 10000, 1000000};
-            
-            float filterValue = 0;
-            
-            for (int j = 0; j < baseCosts.length; j++) {
-                float filter = NewCalculateCostUtil.recursiveEstimateCostOfCriteria(baseCosts[j], node, crit, metadata);
-                
-                filterValue += filter/baseCosts[j];
-            }
-            
-            filterValue /= baseCosts.length;
-   
-            node.setProperty(NodeConstants.Info.EST_SELECTIVITY, new Float(filterValue));
-        }
-    }
-    
-    /**
-     *  Initializes information on the joinRegion about dependency information, etc.
-     *  
-     *  TODO: assumptions are made here about how dependent criteria must look that are a little restrictive
-     */
-    public void initializeJoinInformation() {
-        critieriaToSourceMap = new HashMap<PlanNode, Set<PlanNode>>();
-                
-        LinkedList<PlanNode> crits = new LinkedList<PlanNode>(criteriaNodes);
-        crits.addAll(dependentCritieraNodes);
-        
-        LinkedHashMap<PlanNode, PlanNode> source = new LinkedHashMap<PlanNode, PlanNode>(joinSourceNodes);
-        source.putAll(dependentJoinSourceNodes);
-        
-        for (PlanNode critNode : crits) {
-        	for (GroupSymbol group : critNode.getGroups()) {
-        		for (PlanNode node : source.keySet()) {
-                    if (node.getGroups().contains(group)) {
-                        Set<PlanNode> sources = critieriaToSourceMap.get(critNode);
-                        if (sources == null) {
-                            sources = new HashSet<PlanNode>();
-                            critieriaToSourceMap.put(critNode, sources);
-                        }
-                        sources.add(node);
-                        break;
-                    }
-                }
-            }
-        }            
-
-        if (unsatisfiedAccessPatterns.isEmpty()) {
-            return;
-        }
-        
-        Map<GroupSymbol, PlanNode> dependentGroupToSourceMap = new HashMap<GroupSymbol, PlanNode>();
-        
-        for (PlanNode node : dependentJoinSourceNodes.keySet()) {
-        	for (GroupSymbol symbol : node.getGroups()) {
-                dependentGroupToSourceMap.put(symbol, node);
-            }
-        }
-        
-        for (Iterator<PlanNode> i = getCriteriaNodes().iterator(); i.hasNext();) {
-            PlanNode node = i.next();
-            
-            for (GroupSymbol symbol : node.getGroups()) {
-                if (dependentGroupToSourceMap.containsKey(symbol)) {
-                    i.remove();
-                    dependentCritieraNodes.add(node);
-                    break;
-                }
-            }
-        }
-        
-        dependentCriteriaElements = new HashMap<ElementSymbol, Set<Collection<GroupSymbol>>>();
-        
-        for (PlanNode critNode : dependentCritieraNodes) {
-            Criteria crit = (Criteria)critNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
-            if(!(crit instanceof CompareCriteria)) {
-                continue;
-            }
-            CompareCriteria compCrit = (CompareCriteria) crit;                
-            if(compCrit.getOperator() != CompareCriteria.EQ) {
-                continue;
-            }
-            CompareCriteria compareCriteria = (CompareCriteria)crit;
-            //this may be a proper dependent join criteria
-            Collection<ElementSymbol>[] critElements = new Collection[2];
-            critElements[0] = ElementCollectorVisitor.getElements(compareCriteria.getLeftExpression(), true);
-            if (critElements[0].isEmpty()) {
-            	continue;
-            }
-            critElements[1] = ElementCollectorVisitor.getElements(compareCriteria.getRightExpression(), true);
-            if (critElements[1].isEmpty()) {
-            	continue;
-            }
-            for (int expr = 0; expr < critElements.length; expr++) {
-                //simplifying assumption that there will be a single element on the dependent side
-                if (critElements[expr].size() != 1) {
-                    continue;
-                }
-                ElementSymbol elem = critElements[expr].iterator().next();
-                if (!dependentGroupToSourceMap.containsKey(elem.getGroupSymbol())) {
-                    continue;
-                }
-                //this is also a simplifying assumption.  don't consider criteria that can't be pushed
-                if (containsFunctionsThatCannotBePushed(expr==0?compareCriteria.getRightExpression():compareCriteria.getLeftExpression())) {
-                    continue;
-                }
-                Set<Collection<GroupSymbol>> independentGroups = dependentCriteriaElements.get(elem);
-                if (independentGroups == null) {
-                    independentGroups = new HashSet<Collection<GroupSymbol>>();
-                    dependentCriteriaElements.put(elem, independentGroups);
-                }
-                //set the other side as independent elements
-                independentGroups.add(GroupsUsedByElementsVisitor.getGroups(critElements[(expr+1)%2]));
-            }
-        }
-    }
-    
-    /**
-     * Returns true if the expression is, or contains, any functions that cannot be pushed 
-     * down to the source
-     * @param expression
-     * @return
-     * @since 4.2
-     */
-    private static boolean containsFunctionsThatCannotBePushed(Expression expression) {
-        Iterator functions = FunctionCollectorVisitor.getFunctions(expression, true).iterator();
-        while (functions.hasNext()) {
-            Function function = (Function)functions.next();
-            if (function.getFunctionDescriptor().getPushdown() == FunctionMethod.CANNOT_PUSHDOWN) {
-                return true;
-            }
-        }
-        return false;
-    }
-    
-    public List<PlanNode> getJoinCriteriaForGroups(Set<GroupSymbol> groups) {
-        return getJoinCriteriaForGroups(groups, getCriteriaNodes());
-    }
-    
-    //TODO: this should be better than a linear search
-    protected List<PlanNode> getJoinCriteriaForGroups(Set<GroupSymbol> groups, Collection<PlanNode> nodes) {
-        List<PlanNode> result = new LinkedList<PlanNode>();
-        
-        for (PlanNode critNode : nodes) {
-            if (groups.containsAll(critNode.getGroups())) {
-                result.add(critNode);
-            }
-        }
-        
-        return result;
-    }
-    
-    public void changeJoinOrder(Object[] joinOrder) {
-        List<Map.Entry<PlanNode, PlanNode>> joinSourceEntries = new ArrayList<Map.Entry<PlanNode, PlanNode>>(joinSourceNodes.entrySet());
-        
-        for (int i = 0; i < joinOrder.length; i++) {
-            Integer source = (Integer)joinOrder[i];
-            
-            Map.Entry<PlanNode, PlanNode> entry = joinSourceEntries.get(source.intValue());
-            
-            this.joinSourceNodes.remove(entry.getKey());
-            this.joinSourceNodes.put(entry.getKey(), entry.getValue());
-        }
-    }
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/JoinRegion.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/query/optimizer/relational/rules/JoinRegion.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/JoinRegion.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/JoinRegion.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,513 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.optimizer.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.query.function.metadata.FunctionMethod;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.relational.RelationalPlanner;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants;
+import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.resolver.util.AccessPattern;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+
+
+/**
+ *  A join region is a set of cross and inner joins whose ordering is completely interchangeable.
+ *  
+ *  It can be conceptually thought of as:
+ *     Criteria node some combination of groups A, B, C
+ *     Criteria node some combination of groups A, B, C
+ *     ...
+ *     Join
+ *       JoinSourceA
+ *       JoinSourceB
+ *       JoinSourceC
+ *  
+ *  A full binary join tree is then constructed out of this join region such that all of the
+ *  criteria is pushed to its lowest point.
+ *  
+ */
+class JoinRegion {
+    
+    private PlanNode joinRoot;
+    
+    public static final int UNKNOWN_TUPLE_EST = 100000;
+    
+    private LinkedHashMap<PlanNode, PlanNode> dependentJoinSourceNodes = new LinkedHashMap<PlanNode, PlanNode>();
+    private LinkedHashMap<PlanNode, PlanNode> joinSourceNodes = new LinkedHashMap<PlanNode, PlanNode>();
+        
+    private List<PlanNode> dependentCritieraNodes = new ArrayList<PlanNode>();
+    private List<PlanNode> criteriaNodes = new ArrayList<PlanNode>();
+    
+    private List<Collection<AccessPattern>> unsatisfiedAccessPatterns = new LinkedList<Collection<AccessPattern>>();
+    private boolean containsNestedTable;
+    
+    private Map<ElementSymbol, Set<Collection<GroupSymbol>>> dependentCriteriaElements;
+    private Map<PlanNode, Set<PlanNode>> critieriaToSourceMap;
+    
+    public PlanNode getJoinRoot() {
+        return joinRoot;
+    }
+    
+    public void setContainsNestedTable(boolean containsNestedTable) {
+		this.containsNestedTable = containsNestedTable;
+	}
+    
+    public boolean containsNestedTable() {
+		return containsNestedTable;
+	}
+    
+    public List<Collection<AccessPattern>> getUnsatisfiedAccessPatterns() {
+        return unsatisfiedAccessPatterns;
+    }
+    
+    public Map<PlanNode, PlanNode> getJoinSourceNodes() {
+        return joinSourceNodes;
+    }
+
+    public Map<PlanNode, PlanNode> getDependentJoinSourceNodes() {
+        return dependentJoinSourceNodes;
+    }
+    
+    public List<PlanNode> getCriteriaNodes() {
+        return criteriaNodes;
+    }
+    
+    public List<PlanNode> getDependentCriteriaNodes() {
+        return dependentCritieraNodes;
+    }
+    
+    public Map<ElementSymbol, Set<Collection<GroupSymbol>>> getDependentCriteriaElements() {
+        return this.dependentCriteriaElements;
+    }
+
+    public Map<PlanNode, Set<PlanNode>> getCritieriaToSourceMap() {
+        return this.critieriaToSourceMap;
+    }
+
+    public void addJoinSourceNode(PlanNode sourceNode) {
+        PlanNode root = sourceNode;
+        while (root.getParent() != null && root.getParent().getType() == NodeConstants.Types.SELECT) {
+            root = root.getParent();
+        }
+        if (sourceNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
+            Collection<AccessPattern> aps = (Collection<AccessPattern>)sourceNode.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
+            unsatisfiedAccessPatterns.add(aps);
+            dependentJoinSourceNodes.put(sourceNode, root);
+        } else {
+            joinSourceNodes.put(sourceNode, root);
+        }
+        
+        if (joinRoot == null) {
+            joinRoot = root;
+        }
+    }
+
+    public void addParentCriteria(PlanNode sourceNode) {
+        PlanNode parent = sourceNode.getParent();
+        while (parent != null && parent.getType() == NodeConstants.Types.SELECT) {
+            criteriaNodes.add(parent);
+            sourceNode = parent;
+            parent = parent.getParent();
+        }
+        if (joinRoot == null) {
+            joinRoot = sourceNode;
+        }
+    }
+                    
+    public void addJoinCriteriaList(List<? extends Criteria> joinCriteria) {
+        if (joinCriteria == null || joinCriteria.isEmpty()) {
+            return;
+        }
+        for (Criteria crit : joinCriteria) {
+            criteriaNodes.add(RelationalPlanner.createSelectNode(crit, false));
+        }
+    }
+    
+    /**
+     * This will rebuild the join tree starting at the join root.
+     * 
+     * A left linear tree will be constructed out of the ordering of the 
+     * join sources.
+     * 
+     * Criteria nodes are simply placed at the top of the join region in order
+     * to be pushed by rule PushSelectSriteria.
+     * 
+     */
+    public void reconstructJoinRegoin() {
+        LinkedHashMap<PlanNode, PlanNode> combined = new LinkedHashMap<PlanNode, PlanNode>(joinSourceNodes);
+        combined.putAll(dependentJoinSourceNodes);
+        
+        PlanNode root = null;
+        
+        if (combined.size() < 2) {
+            root = combined.values().iterator().next();
+        } else {
+            root = RulePlanJoins.createJoinNode();
+        
+            for (Map.Entry<PlanNode, PlanNode> entry : combined.entrySet()) {
+                PlanNode joinSourceRoot = entry.getValue();
+                if (root.getChildCount() == 2) {
+                    PlanNode parentJoin = RulePlanJoins.createJoinNode();
+                    parentJoin.addFirstChild(root);
+                    parentJoin.addGroups(root.getGroups());
+                    root = parentJoin;
+                }
+                root.addLastChild(joinSourceRoot);
+                root.addGroups(entry.getKey().getGroups());
+            }
+        }
+        LinkedList<PlanNode> criteria = new LinkedList<PlanNode>(dependentCritieraNodes);
+        criteria.addAll(criteriaNodes);
+
+        PlanNode parent = this.joinRoot.getParent();
+        
+        boolean isLeftChild = parent.getFirstChild() == this.joinRoot;
+
+        parent.removeChild(joinRoot);
+        
+        for (PlanNode critNode : criteria) {
+            critNode.removeFromParent();
+            critNode.removeAllChildren();
+            critNode.addFirstChild(root);
+            root = critNode;
+            critNode.removeProperty(NodeConstants.Info.IS_COPIED);
+            critNode.removeProperty(NodeConstants.Info.EST_CARDINALITY);
+        }
+
+        if (isLeftChild) {
+            parent.addFirstChild(root);
+        } else {
+            parent.addLastChild(root);
+        }
+        this.joinRoot = root;
+    }
+    
+    /**
+     * Will provide an estimate of cost by summing the estimated tuples flowing through
+     * each intermediate join. 
+     *  
+     * @param joinOrder
+     * @param metadata
+     * @return
+     * @throws TeiidComponentException 
+     * @throws QueryMetadataException 
+     */
+    public double scoreRegion(Object[] joinOrder, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
+        List<Map.Entry<PlanNode, PlanNode>> joinSourceEntries = new ArrayList<Map.Entry<PlanNode, PlanNode>>(joinSourceNodes.entrySet());
+        double totalIntermediatCost = 0;
+        double cost = 1;
+        
+        HashSet<PlanNode> criteria = new HashSet<PlanNode>(this.criteriaNodes);
+        HashSet<GroupSymbol> groups = new HashSet<GroupSymbol>(this.joinSourceNodes.size());
+        
+        for (int i = 0; i < joinOrder.length; i++) {
+            Integer source = (Integer)joinOrder[i];
+            
+            Map.Entry<PlanNode, PlanNode> entry = joinSourceEntries.get(source.intValue());
+            PlanNode joinSourceRoot = entry.getValue();
+            
+            //check to make sure that this group ordering satisfies the access patterns
+            if (!this.unsatisfiedAccessPatterns.isEmpty() || this.containsNestedTable) {
+                PlanNode joinSource = entry.getKey();
+                
+                Collection<GroupSymbol> requiredGroups = (Collection<GroupSymbol>)joinSource.getProperty(NodeConstants.Info.REQUIRED_ACCESS_PATTERN_GROUPS);
+                
+                if (requiredGroups != null && !groups.containsAll(requiredGroups)) {
+                    return Double.MAX_VALUE;
+                }
+            }
+            
+            groups.addAll(joinSourceRoot.getGroups());
+            
+            float sourceCost = ((Float)joinSourceRoot.getProperty(NodeConstants.Info.EST_CARDINALITY)).floatValue();
+            
+            List<PlanNode> applicableCriteria = null;
+            
+            if (!criteria.isEmpty() && i > 0) {
+                applicableCriteria = getJoinCriteriaForGroups(groups, criteria);
+            }
+            
+        	if (sourceCost == NewCalculateCostUtil.UNKNOWN_VALUE) {
+        		sourceCost = UNKNOWN_TUPLE_EST;
+                if (applicableCriteria != null && !applicableCriteria.isEmpty()) {
+                	CompoundCriteria cc = new CompoundCriteria();
+                	for (PlanNode planNode : applicableCriteria) {
+    					cc.addCriteria((Criteria) planNode.getProperty(NodeConstants.Info.SELECT_CRITERIA));
+    				}
+                	sourceCost = (float)cost;
+                	criteria.removeAll(applicableCriteria);
+	            	applicableCriteria = null;
+            		if (NewCalculateCostUtil.usesKey(cc, metadata)) {
+    	            	sourceCost = Math.min(UNKNOWN_TUPLE_EST, sourceCost * Math.min(NewCalculateCostUtil.UNKNOWN_JOIN_SCALING, sourceCost));
+            		} else {
+    	            	sourceCost = Math.min(UNKNOWN_TUPLE_EST, sourceCost * Math.min(NewCalculateCostUtil.UNKNOWN_JOIN_SCALING * 2, sourceCost));
+            		}
+                }
+            } else if (Double.isInfinite(sourceCost) || Double.isNaN(sourceCost)) {
+            	return Double.MAX_VALUE;
+            }
+        
+            cost *= sourceCost;
+            
+            if (applicableCriteria != null) {
+                for (PlanNode criteriaNode : applicableCriteria) {
+                    float filter = ((Float)criteriaNode.getProperty(NodeConstants.Info.EST_SELECTIVITY)).floatValue();
+                    
+                    cost *= filter;
+                }
+                
+                criteria.removeAll(applicableCriteria);
+            }
+            totalIntermediatCost += cost;
+        }
+        
+        return totalIntermediatCost;
+    }
+    
+    /**
+     *  Returns true if every element in an unsatisfied access pattern can be satisfied by the current join criteria
+     *  This does not necessarily mean that a join tree will be successfully created
+     */
+    public boolean isSatisfiable() {
+    	for (Collection<AccessPattern> accessPatterns : getUnsatisfiedAccessPatterns()) {
+            boolean matchedAll = false;
+            for (AccessPattern ap : accessPatterns) {
+                if (dependentCriteriaElements.keySet().containsAll(ap.getUnsatisfied())) {
+                    matchedAll = true;
+                    break;
+                }
+            }
+            if (!matchedAll) {
+                return false;
+            }
+        }
+        
+        return true;
+    }
+
+    public void initializeCostingInformation(QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
+    	for (PlanNode node : joinSourceNodes.values()) {
+            NewCalculateCostUtil.computeCostForTree(node, metadata);
+        }
+        
+        estimateCriteriaSelectivity(metadata);        
+    }
+
+    /** 
+     * @param metadata
+     * @throws QueryMetadataException
+     * @throws TeiidComponentException
+     */
+    private void estimateCriteriaSelectivity(QueryMetadataInterface metadata) throws QueryMetadataException,
+                                                                             TeiidComponentException {
+        for (PlanNode node : criteriaNodes) {
+            Criteria crit = (Criteria)node.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+            
+            float[] baseCosts = new float[] {100, 10000, 1000000};
+            
+            float filterValue = 0;
+            
+            for (int j = 0; j < baseCosts.length; j++) {
+                float filter = NewCalculateCostUtil.recursiveEstimateCostOfCriteria(baseCosts[j], node, crit, metadata);
+                
+                filterValue += filter/baseCosts[j];
+            }
+            
+            filterValue /= baseCosts.length;
+   
+            node.setProperty(NodeConstants.Info.EST_SELECTIVITY, new Float(filterValue));
+        }
+    }
+    
+    /**
+     *  Initializes information on the joinRegion about dependency information, etc.
+     *  
+     *  TODO: assumptions are made here about how dependent criteria must look that are a little restrictive
+     */
+    public void initializeJoinInformation() {
+        critieriaToSourceMap = new HashMap<PlanNode, Set<PlanNode>>();
+                
+        LinkedList<PlanNode> crits = new LinkedList<PlanNode>(criteriaNodes);
+        crits.addAll(dependentCritieraNodes);
+        
+        LinkedHashMap<PlanNode, PlanNode> source = new LinkedHashMap<PlanNode, PlanNode>(joinSourceNodes);
+        source.putAll(dependentJoinSourceNodes);
+        
+        for (PlanNode critNode : crits) {
+        	for (GroupSymbol group : critNode.getGroups()) {
+        		for (PlanNode node : source.keySet()) {
+                    if (node.getGroups().contains(group)) {
+                        Set<PlanNode> sources = critieriaToSourceMap.get(critNode);
+                        if (sources == null) {
+                            sources = new HashSet<PlanNode>();
+                            critieriaToSourceMap.put(critNode, sources);
+                        }
+                        sources.add(node);
+                        break;
+                    }
+                }
+            }
+        }            
+
+        if (unsatisfiedAccessPatterns.isEmpty()) {
+            return;
+        }
+        
+        Map<GroupSymbol, PlanNode> dependentGroupToSourceMap = new HashMap<GroupSymbol, PlanNode>();
+        
+        for (PlanNode node : dependentJoinSourceNodes.keySet()) {
+        	for (GroupSymbol symbol : node.getGroups()) {
+                dependentGroupToSourceMap.put(symbol, node);
+            }
+        }
+        
+        for (Iterator<PlanNode> i = getCriteriaNodes().iterator(); i.hasNext();) {
+            PlanNode node = i.next();
+            
+            for (GroupSymbol symbol : node.getGroups()) {
+                if (dependentGroupToSourceMap.containsKey(symbol)) {
+                    i.remove();
+                    dependentCritieraNodes.add(node);
+                    break;
+                }
+            }
+        }
+        
+        dependentCriteriaElements = new HashMap<ElementSymbol, Set<Collection<GroupSymbol>>>();
+        
+        for (PlanNode critNode : dependentCritieraNodes) {
+            Criteria crit = (Criteria)critNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+            if(!(crit instanceof CompareCriteria)) {
+                continue;
+            }
+            CompareCriteria compCrit = (CompareCriteria) crit;                
+            if(compCrit.getOperator() != CompareCriteria.EQ) {
+                continue;
+            }
+            CompareCriteria compareCriteria = (CompareCriteria)crit;
+            //this may be a proper dependent join criteria
+            Collection<ElementSymbol>[] critElements = new Collection[2];
+            critElements[0] = ElementCollectorVisitor.getElements(compareCriteria.getLeftExpression(), true);
+            if (critElements[0].isEmpty()) {
+            	continue;
+            }
+            critElements[1] = ElementCollectorVisitor.getElements(compareCriteria.getRightExpression(), true);
+            if (critElements[1].isEmpty()) {
+            	continue;
+            }
+            for (int expr = 0; expr < critElements.length; expr++) {
+                //simplifying assumption that there will be a single element on the dependent side
+                if (critElements[expr].size() != 1) {
+                    continue;
+                }
+                ElementSymbol elem = critElements[expr].iterator().next();
+                if (!dependentGroupToSourceMap.containsKey(elem.getGroupSymbol())) {
+                    continue;
+                }
+                //this is also a simplifying assumption.  don't consider criteria that can't be pushed
+                if (containsFunctionsThatCannotBePushed(expr==0?compareCriteria.getRightExpression():compareCriteria.getLeftExpression())) {
+                    continue;
+                }
+                Set<Collection<GroupSymbol>> independentGroups = dependentCriteriaElements.get(elem);
+                if (independentGroups == null) {
+                    independentGroups = new HashSet<Collection<GroupSymbol>>();
+                    dependentCriteriaElements.put(elem, independentGroups);
+                }
+                //set the other side as independent elements
+                independentGroups.add(GroupsUsedByElementsVisitor.getGroups(critElements[(expr+1)%2]));
+            }
+        }
+    }
+    
+    /**
+     * Returns true if the expression is, or contains, any functions that cannot be pushed 
+     * down to the source
+     * @param expression
+     * @return
+     * @since 4.2
+     */
+    private static boolean containsFunctionsThatCannotBePushed(Expression expression) {
+        Iterator functions = FunctionCollectorVisitor.getFunctions(expression, true).iterator();
+        while (functions.hasNext()) {
+            Function function = (Function)functions.next();
+            if (function.getFunctionDescriptor().getPushdown() == FunctionMethod.CANNOT_PUSHDOWN) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    public List<PlanNode> getJoinCriteriaForGroups(Set<GroupSymbol> groups) {
+        return getJoinCriteriaForGroups(groups, getCriteriaNodes());
+    }
+    
+    //TODO: this should be better than a linear search
+    protected List<PlanNode> getJoinCriteriaForGroups(Set<GroupSymbol> groups, Collection<PlanNode> nodes) {
+        List<PlanNode> result = new LinkedList<PlanNode>();
+        
+        for (PlanNode critNode : nodes) {
+            if (groups.containsAll(critNode.getGroups())) {
+                result.add(critNode);
+            }
+        }
+        
+        return result;
+    }
+    
+    public void changeJoinOrder(Object[] joinOrder) {
+        List<Map.Entry<PlanNode, PlanNode>> joinSourceEntries = new ArrayList<Map.Entry<PlanNode, PlanNode>>(joinSourceNodes.entrySet());
+        
+        for (int i = 0; i < joinOrder.length; i++) {
+            Integer source = (Integer)joinOrder[i];
+            
+            Map.Entry<PlanNode, PlanNode> entry = joinSourceEntries.get(source.intValue());
+            
+            this.joinSourceNodes.remove(entry.getKey());
+            this.joinSourceNodes.put(entry.getKey(), entry.getValue());
+        }
+    }
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,1100 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.optimizer.relational.rules;
-
-import java.sql.Date;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.SupportConstants;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.relational.plantree.NodeConstants;
-import org.teiid.query.optimizer.relational.plantree.NodeEditor;
-import org.teiid.query.optimizer.relational.plantree.PlanNode;
-import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
-import org.teiid.query.sql.lang.AbstractSetCriteria;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.NotCriteria;
-import org.teiid.query.sql.lang.PredicateCriteria;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.EvaluatableVisitor;
-import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
-import org.teiid.query.util.CommandContext;
-
-/** 
- * @since 4.3
- */
-public class NewCalculateCostUtil {
-
-    public static final int UNKNOWN_JOIN_SCALING = 20;
-	public static final float UNKNOWN_VALUE = -1;
-    
-    // the following variables are used to hold cost estimates (roughly in milliseconds)
-    private final static float compareTime = .05f; //TODO: a better estimate would be based upon the number of conjuncts
-    private final static float readTime = .001f; //TODO: should come from the connector
-    private final static float procNewRequestTime = 100; //TODO: should come from the connector
-    private final static float procMoreRequestTime = 15; //TODO: should come from the connector
-    
-    /**
-     * Calculate cost of a node and all children, recursively from the bottom up.
-     * @param node
-     * @param metadata
-     * @return Cost computed at the passed node
-     * @throws QueryMetadataException
-     * @throws TeiidComponentException
-     */
-    static float computeCostForTree(PlanNode node, QueryMetadataInterface metadata) 
-        throws QueryMetadataException, TeiidComponentException {
-
-        Float cost = (Float) node.getProperty(NodeConstants.Info.EST_CARDINALITY);
-
-    	// check if already computed
-        if(cost == null) {
-        	for (PlanNode child : node.getChildren()) {
-        		computeCostForTree(child, metadata);
-            }
-            computeNodeCost(node, metadata);
-            cost = (Float) node.getProperty(NodeConstants.Info.EST_CARDINALITY); 
-        }
-        
-        if(cost != null) {
-            return cost.floatValue();
-        } 
-        
-        return UNKNOWN_VALUE;
-    }
-   
-    /**
-     * This method attempts to estimate a cost for each type of node.
-     * @param node
-     * @param metadata
-     * @throws QueryMetadataException
-     * @throws TeiidComponentException
-     */
-    private static void computeNodeCost(PlanNode node, QueryMetadataInterface metadata) 
-        throws QueryMetadataException, TeiidComponentException {
-        
-        switch(node.getType()) {
-            case NodeConstants.Types.SOURCE:
-                estimateSourceNodeCost(node, metadata);
-                break;
-
-            case NodeConstants.Types.SELECT:
-                estimateSelectNodeCost(node, metadata);
-                break;
-                           
-            case NodeConstants.Types.JOIN:
-                estimateJoinNodeCost(node, metadata);
-                break;
-
-            case NodeConstants.Types.DUP_REMOVE:
-                estimateNodeCost(node, FrameUtil.findTopCols(node), metadata);
-                break;
-
-            case NodeConstants.Types.GROUP:
-            	if (!node.hasCollectionProperty(NodeConstants.Info.GROUP_COLS)) {
-            		setCardinalityEstimate(node, 1f);
-            	} else {
-            		estimateNodeCost(node, (List)node.getProperty(NodeConstants.Info.GROUP_COLS), metadata);
-            	}
-                break;
-            case NodeConstants.Types.ACCESS:
-            case NodeConstants.Types.SORT:
-            {
-                //Simply record the cost of the only child
-                PlanNode child = node.getFirstChild();
-                Float childCost = (Float)child.getProperty(NodeConstants.Info.EST_CARDINALITY);
-                setCardinalityEstimate(node, childCost);
-                break;
-            }
-            case NodeConstants.Types.NULL:
-                setCardinalityEstimate(node, 0f);
-                break;
-
-            case NodeConstants.Types.PROJECT:
-            {
-                Float childCost = null;
-                //Simply record the cost of the only child
-                if (node.getChildCount() != 0) {
-                    PlanNode child = node.getFirstChild();
-                    childCost = (Float)child.getProperty(NodeConstants.Info.EST_CARDINALITY);
-                } else {
-                    childCost = 1f;
-                }
-                setCardinalityEstimate(node, childCost);
-                break;
-            }
-            case NodeConstants.Types.SET_OP: 
-            {
-                estimateSetOpCost(node, metadata);
-                break;
-            }
-            case NodeConstants.Types.TUPLE_LIMIT: 
-            {
-                PlanNode child = node.getFirstChild();
-                float childCost = child.getCardinality();
-                
-                Expression offset = (Expression)node.getProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT);
-                Float cost = childCost;
-                
-                if (childCost != UNKNOWN_VALUE && offset instanceof Constant) {
-                    float offsetCost = childCost - ((Number)((Constant)offset).getValue()).floatValue();
-                    cost = new Float((offsetCost < 0) ? 0 : offsetCost);
-                }
-                
-                Expression limit = (Expression)node.getProperty(NodeConstants.Info.MAX_TUPLE_LIMIT);
-                if (limit instanceof Constant) {
-                    float limitCost = ((Number)((Constant)limit).getValue()).floatValue();
-                    if (cost.floatValue() != UNKNOWN_VALUE) {
-                        cost = new Float(Math.min(limitCost, cost.floatValue()));
-                    } else {
-                        cost = new Float(limitCost);
-                    }
-                } 
-                setCardinalityEstimate(node, cost);
-                break;
-            }
-        }
-    }
-
-	private static void estimateSetOpCost(PlanNode node,
-			QueryMetadataInterface metadata) throws QueryMetadataException,
-			TeiidComponentException {
-		float cost = 0;
-		
-		SetQuery.Operation op = (SetQuery.Operation)node.getProperty(NodeConstants.Info.SET_OPERATION);
-
-		float leftCost = (Float)node.getFirstChild().getProperty(NodeConstants.Info.EST_CARDINALITY);
-		float rightCost = (Float)node.getLastChild().getProperty(NodeConstants.Info.EST_CARDINALITY);
-		
-		if (!node.hasBooleanProperty(NodeConstants.Info.USE_ALL)) {
-			leftCost = getDistinctEstimate(node.getFirstChild(), metadata, leftCost);
-			rightCost = getDistinctEstimate(node.getLastChild(), metadata, rightCost);
-		}
-		
-		cost = leftCost;
-		
-		switch (op) {
-		case EXCEPT:
-			if (leftCost != UNKNOWN_VALUE && rightCost != UNKNOWN_VALUE) {
-		    	cost = Math.max(1, leftCost - .5f * rightCost);
-		    }
-			break;
-		case INTERSECT:
-			if (rightCost != UNKNOWN_VALUE) {
-				if (leftCost != UNKNOWN_VALUE) {
-		    		cost = .5f * Math.min(leftCost, rightCost);
-				} else {
-					cost = rightCost;
-				}
-			}
-			break;
-		default: //union
-			if (leftCost != UNKNOWN_VALUE && rightCost != UNKNOWN_VALUE) {
-		        if (!node.hasBooleanProperty(NodeConstants.Info.USE_ALL)) {
-		        	cost = Math.max(leftCost, rightCost) + .5f * Math.min(leftCost, rightCost);
-		        } else {
-		            cost = rightCost + leftCost;
-		        }
-			}
-			break;
-		}
-		
-		setCardinalityEstimate(node, new Float(cost));
-	}
-
-	private static float getDistinctEstimate(PlanNode node,
-			QueryMetadataInterface metadata, float cost)
-			throws QueryMetadataException, TeiidComponentException {
-		PlanNode projectNode = NodeEditor.findNodePreOrder(node, NodeConstants.Types.PROJECT);
-		if (projectNode != null) {
-			cost = getDistinctEstimate(projectNode, (List)projectNode.getProperty(NodeConstants.Info.PROJECT_COLS), metadata, cost);
-		}
-		return cost;
-	}
-
-    private static void setCardinalityEstimate(PlanNode node, Float bestEstimate) {
-        if (bestEstimate == null){
-        	bestEstimate = Float.valueOf(UNKNOWN_VALUE);
-        }
-        node.setProperty(NodeConstants.Info.EST_CARDINALITY, bestEstimate);
-    }
-
-    /**
-     * Method estimateJoinNodeCost.
-     * @param node
-     * @param metadata
-     */
-    private static void estimateJoinNodeCost(PlanNode node, QueryMetadataInterface metadata)
-        throws QueryMetadataException, TeiidComponentException {
-
-        Iterator<PlanNode> children = node.getChildren().iterator();
-        PlanNode child1 = children.next();
-        float childCost1 = child1.getCardinality();
-        PlanNode child2 = children.next();
-        float childCost2 = child2.getCardinality();
-        
-        if (childCost1 == UNKNOWN_VALUE || childCost2 == UNKNOWN_VALUE) {
-        	setCardinalityEstimate(node, null);
-        	return;
-        }
-
-        JoinType joinType = (JoinType)node.getProperty(NodeConstants.Info.JOIN_TYPE);
-        List joinCriteria = (List) node.getProperty(NodeConstants.Info.JOIN_CRITERIA);
-        
-        float baseCost = childCost1 * childCost2;
-
-        if (joinCriteria != null && !joinCriteria.isEmpty()) {
-    		Criteria crit = Criteria.combineCriteria(joinCriteria);
-    		//TODO: we may be able to get a fairly accurate join estimate if the
-    		//unknown side is being joined with a key
-        	baseCost = recursiveEstimateCostOfCriteria(baseCost, node, crit, metadata);
-        }
-        
-        Float cost = null;
-        if (JoinType.JOIN_CROSS.equals(joinType)){
-            cost = new Float(baseCost);
-        } else if (JoinType.JOIN_FULL_OUTER.equals(joinType)) {
-            cost = new Float(Math.max((childCost1+childCost2),baseCost));
-        } else if (JoinType.JOIN_LEFT_OUTER.equals(joinType)) {
-            cost = new Float(Math.max(childCost1,baseCost));
-        } else if (JoinType.JOIN_RIGHT_OUTER.equals(joinType)) {
-            cost = new Float(Math.max(childCost2,baseCost));
-        } else if (JoinType.JOIN_INNER.equals(joinType)) {
-            cost = new Float(baseCost);
-        }
-        
-        setCardinalityEstimate(node, cost);
-    }
-
-    /**
-     * Estimate the cost of a selection.  This is not easy to do without information 
-     * about the value count for each relation attribute.  
-     * @param metadata
-     */
-    private static void estimateSelectNodeCost(PlanNode node, QueryMetadataInterface metadata) 
-        throws QueryMetadataException, TeiidComponentException {
-
-        PlanNode child = node.getFirstChild();
-        float childCost = child.getCardinality();
-        
-        //Get list of conjuncts
-        Criteria selectCriteria = (Criteria)node.getProperty(NodeConstants.Info.SELECT_CRITERIA);
-        float newCost = recursiveEstimateCostOfCriteria(childCost, node, selectCriteria, metadata);
-        setCardinalityEstimate(node, new Float(newCost));
-    }
-
-    /**
-     * For a source node, the cost is basically the cardinality of the source
-     * (if it is known).
-     * @param node
-     * @param metadata
-     * @throws QueryMetadataException
-     * @throws TeiidComponentException
-     */
-    private static void estimateSourceNodeCost(PlanNode node, QueryMetadataInterface metadata) 
-        throws QueryMetadataException, TeiidComponentException {
-        
-        float cost = UNKNOWN_VALUE;
-        if(node.getChildCount() > 0) {
-        	SymbolMap references = (SymbolMap)node.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
-        	//only cost non-correlated TODO: a better estimate for correlated
-        	if (references == null) {
-	            PlanNode child = node.getFirstChild();
-	            cost = child.getCardinality();
-        	}
-        }else {
-            GroupSymbol group = node.getGroups().iterator().next();
-            float cardinality = metadata.getCardinality(group.getMetadataID());
-            if (cardinality <= QueryMetadataInterface.UNKNOWN_CARDINALITY){
-                cardinality = UNKNOWN_VALUE;
-            }
-            cost = cardinality;
-        }
-        
-        setCardinalityEstimate(node, new Float(cost));
-    } 
-    
-    /**
-     * For a Group or Dup Removal node, the cost is basically the smaller of the largest NDV of the 
-     * selected columns and cost of the child node (if it is known).
-     * @param node
-     * @param metadata
-     * @throws QueryMetadataException
-     * @throws TeiidComponentException
-     */
-    private static void estimateNodeCost(PlanNode node, List expressions, QueryMetadataInterface metadata) 
-        throws QueryMetadataException, TeiidComponentException {
-        
-        PlanNode child = node.getFirstChild();
-        float childCost = child.getCardinality();
-        
-        if(childCost == UNKNOWN_VALUE) {
-            setCardinalityEstimate(node, null);
-            return;
-        }
-
-        Float newCost = getDistinctEstimate(node, expressions, metadata, childCost);
-        setCardinalityEstimate(node, newCost);
-    }
-
-    private static Float getDistinctEstimate(PlanNode node,
-                                             List elements,
-                                             QueryMetadataInterface metadata,
-                                             float childCost) throws QueryMetadataException,
-                                                             TeiidComponentException {
-        if(elements == null) {
-            return new Float(childCost);
-        }
-        HashSet<ElementSymbol> elems = new HashSet<ElementSymbol>();
-        ElementCollectorVisitor.getElements(elements, elems);
-        if (usesKey(elements, metadata)) {
-        	return new Float(childCost);
-        }
-        float ndvCost = getNDV(elems, node, childCost, metadata);
-        if(ndvCost == UNKNOWN_VALUE) {
-            ndvCost = childCost;
-        }
-        
-        Float newCost = new Float(Math.min(childCost, ndvCost));
-        return newCost;
-    }
-    
-    static float recursiveEstimateCostOfCriteria(float childCost, PlanNode currentNode, Criteria crit, QueryMetadataInterface metadata)
-        throws QueryMetadataException, TeiidComponentException {
-        
-        float cost = childCost; 
-        if(crit instanceof CompoundCriteria) {
-            CompoundCriteria compCrit = (CompoundCriteria) crit;
-            if (compCrit.getOperator() == CompoundCriteria.OR) {
-                cost = 0;
-            } 
-            if (usesKey(compCrit, metadata)) {
-                return 1;
-            }
-            for (Criteria critPart : compCrit.getCriteria()) {
-                float nextCost = recursiveEstimateCostOfCriteria(childCost, currentNode, critPart, metadata);
-                
-                if(compCrit.getOperator() == CompoundCriteria.AND) {
-                    if (nextCost == UNKNOWN_VALUE) {
-                        continue;
-                    }
-                    if (childCost != UNKNOWN_VALUE) {
-                        cost *= nextCost/childCost;
-                    } else {
-                        if (cost == UNKNOWN_VALUE) {
-                            cost = nextCost;
-                        } else {
-                            cost = Math.min(cost, nextCost);
-                        }
-                    }
-                    if (cost <= 1) {
-                        return 1;
-                    }
-                } else {
-                    if (nextCost == UNKNOWN_VALUE) {
-                        return childCost;
-                    } 
-                    //this assumes that all disjuncts are completely disjoint
-                    cost += nextCost;
-                    if (childCost != UNKNOWN_VALUE) {
-                        cost = Math.min(cost, childCost);
-                    }
-                }
-            }
-            if (cost == UNKNOWN_VALUE) {
-                return childCost;
-            }
-        } else if(crit instanceof NotCriteria){
-            if (childCost == UNKNOWN_VALUE) {
-                return UNKNOWN_VALUE;
-            }
-            float nextCost = recursiveEstimateCostOfCriteria(childCost, currentNode, ((NotCriteria)crit).getCriteria(), metadata);
-            if (nextCost == UNKNOWN_VALUE){
-                return childCost;
-            }   
-            cost -= nextCost;
-        } else {
-            cost = estimatePredicateCost(childCost, currentNode, (PredicateCriteria) crit, metadata);
-            
-            if (cost == UNKNOWN_VALUE) {
-                return childCost;
-            }
-        }  
-        
-        cost = Math.max(cost, 1);
-        
-        return cost;
-    }
-    
-    /** 
-     * This method is a helper to examine whether a compound criteria covers
-     * a compound key.  A "valid" criteria is 
-     * 1) a predicate criteria
-     *   1a) not negated
-     *   1b) with an equality operator if it is a compare criteria
-     * b) or a compound criteria containing valid criteria and an "AND" operator 
-     * @param criteria
-     * @param elements Collection to collect ElementSymbols in
-     * @since 4.2
-     */
-    private static void collectElementsOfValidCriteria(Criteria criteria, Collection<ElementSymbol> elements) {
-       
-        if(criteria instanceof CompoundCriteria) {
-            CompoundCriteria compCrit = (CompoundCriteria) criteria;
-            Iterator<Criteria> iter = compCrit.getCriteria().iterator();
-            boolean first = true;
-            Collection<ElementSymbol> savedElements = elements;
-            if(compCrit.getOperator() == CompoundCriteria.OR) {
-            	elements = new HashSet<ElementSymbol>();
-            }
-            while(iter.hasNext()) { 
-            	if(compCrit.getOperator() == CompoundCriteria.AND || first) {
-            		collectElementsOfValidCriteria(iter.next(), elements);
-            		first = false;
-            	} else {
-            		HashSet<ElementSymbol> other = new HashSet<ElementSymbol>();
-            		collectElementsOfValidCriteria(iter.next(), other);
-            		elements.retainAll(other);
-            	}
-            }
-            if (compCrit.getOperator() == CompoundCriteria.OR) {
-            	savedElements.addAll(elements);
-            }
-        } else if(criteria instanceof CompareCriteria) {
-            CompareCriteria compCrit = (CompareCriteria)criteria;
-            if (compCrit.getOperator() == CompareCriteria.EQ){
-                ElementCollectorVisitor.getElements(compCrit, elements);
-            }                 
-        } else if(criteria instanceof MatchCriteria) {
-            MatchCriteria matchCriteria = (MatchCriteria)criteria;
-            if (!matchCriteria.isNegated()) {
-                ElementCollectorVisitor.getElements(matchCriteria, elements);
-            }
-
-        } else if(criteria instanceof AbstractSetCriteria) {
-            AbstractSetCriteria setCriteria = (AbstractSetCriteria)criteria;
-            if (!setCriteria.isNegated()) {
-                ElementCollectorVisitor.getElements(setCriteria.getExpression(), elements);
-            }
-        } else if(criteria instanceof IsNullCriteria) {
-            IsNullCriteria isNullCriteria = (IsNullCriteria)criteria;
-            if (!isNullCriteria.isNegated()) {
-                ElementCollectorVisitor.getElements(isNullCriteria.getExpression(), elements);
-            }
-        }        
-    }
-    
-    /** 
-     * @param childCost
-     * @param predicateCriteria
-     * @param metadata
-     * @return
-     * @since 4.3
-     */
-    private static float estimatePredicateCost(float childCost, PlanNode currentNode, PredicateCriteria predicateCriteria, QueryMetadataInterface metadata)
-        throws QueryMetadataException, TeiidComponentException {
-        
-        Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(predicateCriteria, true);
-        
-        Collection<GroupSymbol> groups = GroupsUsedByElementsVisitor.getGroups(elements);
-        boolean multiGroup = groups.size() > 1;
-        
-        float cost = childCost;
-        float ndv = getNDV(elements, currentNode, childCost, metadata);
-        
-        boolean unknownChildCost = childCost == UNKNOWN_VALUE;
-        boolean usesKey = usesKey(elements, metadata);
-        
-        if (childCost == UNKNOWN_VALUE) {
-            childCost = 1;
-        }
-
-        if (ndv == UNKNOWN_VALUE) {
-            ndv = 3;
-            if (multiGroup) {
-                if (usesKey) {
-                    ndv = (float)Math.ceil(Math.sqrt(childCost));
-                } else {
-                    ndv = (float)Math.ceil(Math.sqrt(childCost)/4);
-                }
-                ndv = Math.max(ndv, 1);
-            } else if (usesKey) {
-                ndv = childCost;
-            }
-        } 
-                
-        boolean isNegatedPredicateCriteria = false;
-        if(predicateCriteria instanceof CompareCriteria) {
-            CompareCriteria compCrit = (CompareCriteria) predicateCriteria;
-                        
-            if (compCrit.getOperator() == CompareCriteria.EQ || compCrit.getOperator() == CompareCriteria.NE){
-                if (unknownChildCost && (!usesKey || multiGroup)) {
-                    return UNKNOWN_VALUE;
-                }
-                cost = childCost / ndv;
-                if (compCrit.getOperator() == CompareCriteria.NE) {
-                    isNegatedPredicateCriteria = true;
-                }
-            } else { //GE, LE, GT, LT
-                cost = getCostForComparison(childCost, metadata, compCrit, unknownChildCost);
-            }
-        } else if(predicateCriteria instanceof MatchCriteria) {
-            MatchCriteria matchCriteria = (MatchCriteria)predicateCriteria;
-            if (unknownChildCost) {
-                return UNKNOWN_VALUE;
-            }
-            cost = estimateMatchCost(childCost, ndv, matchCriteria);
-            
-            isNegatedPredicateCriteria = matchCriteria.isNegated();
-
-        } else if(predicateCriteria instanceof SetCriteria) {
-            SetCriteria setCriteria = (SetCriteria) predicateCriteria;
-            if (unknownChildCost) {
-                return UNKNOWN_VALUE;
-            }
-            cost = childCost * setCriteria.getNumberOfValues() / ndv;
-            
-            isNegatedPredicateCriteria = setCriteria.isNegated();
-            
-        } else if(predicateCriteria instanceof SubquerySetCriteria) {
-            SubquerySetCriteria setCriteria = (SubquerySetCriteria) predicateCriteria;
-            
-            // TODO - use inner ProcessorPlan cardinality estimates 
-            // to determine the estimated number of values
-            if (unknownChildCost) {
-                return UNKNOWN_VALUE;
-            }
-            cost = childCost / 3;
-            
-            isNegatedPredicateCriteria = setCriteria.isNegated();
-
-        } else if(predicateCriteria instanceof IsNullCriteria) {
-            IsNullCriteria isNullCriteria = (IsNullCriteria)predicateCriteria;
-
-            float nnv = getNNV(elements, currentNode, childCost, metadata);
-            if (nnv == UNKNOWN_VALUE) {
-            	if (unknownChildCost) {
-            		return UNKNOWN_VALUE;
-            	}
-                cost = childCost / ndv;
-            } else {
-                cost = nnv;
-            }
-            
-            isNegatedPredicateCriteria = isNullCriteria.isNegated();
-        }
-
-        if (cost == UNKNOWN_VALUE) {
-            return UNKNOWN_VALUE;
-        }
-        
-        if (cost > childCost) {
-            cost = childCost;
-        }
-        
-        if (isNegatedPredicateCriteria) {
-            // estimate for NOT in the predicate
-            cost = (cost != UNKNOWN_VALUE)
-                    ? Math.max( childCost - cost, 1)
-                    : UNKNOWN_VALUE;
-        }
-                
-        return cost;
-    }
-
-    /** 
-     * TODO: does not check for escape char
-     * or if it will contain single match chars
-     */
-    private static float estimateMatchCost(float childCost,
-                                           float ndv,
-                                           MatchCriteria criteria) {
-        Expression matchExpression = criteria.getRightExpression();
-        if(matchExpression instanceof Constant && ((Constant)matchExpression).getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
-            String compareValue = (String) ((Constant)matchExpression).getValue();
-            if(compareValue != null && compareValue.indexOf('%') < 0) {
-            	return (childCost / 2) * (1 / 3f  + 1 / ndv); //without knowing length constraints we'll make an average guess
-            }
-        } else if (EvaluatableVisitor.willBecomeConstant(criteria.getLeftExpression())) {
-            return childCost / ndv;
-        }
-        return childCost / 3;
-    }
-
-    private static float getCostForComparison(float childCost,
-                                              QueryMetadataInterface metadata,
-                                              CompareCriteria compCrit, boolean unknownChildCost) throws TeiidComponentException,
-                                                                       QueryMetadataException {
-        if (!(compCrit.getLeftExpression() instanceof ElementSymbol) || !(compCrit.getRightExpression() instanceof Constant)) {
-            if (unknownChildCost) {
-                return UNKNOWN_VALUE;
-            }
-            return childCost/3;
-        }
-        ElementSymbol element = (ElementSymbol)compCrit.getLeftExpression();
-        Class dataType = compCrit.getRightExpression().getType();
-    
-        String max = (String)metadata.getMaximumValue(element.getMetadataID());
-        String min = (String)metadata.getMinimumValue(element.getMetadataID());
-        if(max == null || min == null) {
-            if (unknownChildCost) {
-                return UNKNOWN_VALUE;
-            }
-            return childCost/3;
-        } 
-        float cost = childCost;
-        try{
-            float maxValue = 0;
-            float minValue = 0;
-
-            Constant value = (Constant)compCrit.getRightExpression();
-            float compareValue = 0;
-        	// Case 6257 - handling added for time and date.  If the max/min values are not
-            // in the expected format, NumberFormatException is thrown and reverts to default costing.
-            if(dataType.equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
-                compareValue = ((Timestamp)value.getValue()).getTime();
-                maxValue = Timestamp.valueOf(max).getTime();
-                minValue = Timestamp.valueOf(min).getTime();
-            } else if(dataType.equals(DataTypeManager.DefaultDataClasses.TIME)) {
-                compareValue = ((Time)value.getValue()).getTime();
-                maxValue = Time.valueOf(max).getTime();
-                minValue = Time.valueOf(min).getTime();
-            // (For date, our costing sets the max and min values using timestamp format)
-            } else if(dataType.equals(DataTypeManager.DefaultDataClasses.DATE)) {
-                compareValue = ((Date)value.getValue()).getTime();
-                maxValue = Timestamp.valueOf(max).getTime();
-                minValue = Timestamp.valueOf(min).getTime();
-            } else {
-            	if(!Number.class.isAssignableFrom(dataType)) {
-                    if (unknownChildCost) {
-                        return UNKNOWN_VALUE;
-                    }
-                    return childCost/3;
-                }
-                compareValue = ((Number)value.getValue()).floatValue();
-                maxValue = Integer.parseInt(max);
-                minValue = Integer.parseInt(min);
-            }
-            float range = Math.max(maxValue - minValue, 1);
-            
-            float costMultiple = 1;
-            
-            if(compCrit.getOperator() == CompareCriteria.GT || compCrit.getOperator() == CompareCriteria.GE) {
-            	costMultiple = (maxValue - compareValue)/range;
-                if (compareValue < 0 && maxValue < 0) {
-                	costMultiple = (1 - costMultiple);
-                }
-            } else if(compCrit.getOperator() == CompareCriteria.LT || compCrit.getOperator() == CompareCriteria.LE) {
-            	costMultiple = (compareValue - minValue)/range;
-                if (compareValue < 0 && minValue < 0) {
-                	costMultiple = (1 - costMultiple);
-                }
-            }
-            if (costMultiple > 1) {
-            	costMultiple = 1;
-            } else if (costMultiple < 0) {
-            	costMultiple = 0;
-            }
-            cost = childCost * costMultiple;
-        }catch(IllegalArgumentException e) {
-            LogManager.logWarning(LogConstants.CTX_QUERY_PLANNER, e, QueryPlugin.Util.getString("NewCalculateCostUtil.badCost")); //$NON-NLS-1$
-            // If we were unable to parse the timestamp we will revert to the divide by three estimate
-            if (unknownChildCost) {
-                return UNKNOWN_VALUE;
-            }
-            cost = childCost/3;
-        }
-        return cost;
-    }
-    
-    static boolean usesKey(PlanNode planNode, Collection<? extends SingleElementSymbol> allElements, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
-    	return NodeEditor.findAllNodes(planNode, NodeConstants.Types.SOURCE, NodeConstants.Types.JOIN | NodeConstants.Types.SET_OP).size() == 1
-    	&& usesKey(allElements, metadata);
-    }
-    
-    public static boolean usesKey(Criteria crit, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
-        HashSet<ElementSymbol> elements = new HashSet<ElementSymbol>();
-        collectElementsOfValidCriteria(crit, elements);
-        return usesKey(elements, metadata);
-    }
-    
-    /**
-     * TODO: this uses key check is not really accurate, it doesn't take into consideration where 
-     * we are in the plan.
-     * if a key column is used after a non 1-1 join or a union all, then it may be non-unique.
-     */
-    private static boolean usesKey(Collection<? extends SingleElementSymbol> allElements, QueryMetadataInterface metadata)
-        throws QueryMetadataException, TeiidComponentException {
-    
-        if(allElements == null || allElements.size() == 0) { 
-            return false;
-        }    
-     
-        // Sort elements into groups
-        Map<GroupSymbol, List<Object>> groupMap = new HashMap<GroupSymbol, List<Object>>();
-        for (SingleElementSymbol ses : allElements) {
-        	if (!(ses instanceof ElementSymbol)) {
-        		continue;
-        	}
-        	ElementSymbol element = (ElementSymbol)ses;
-            GroupSymbol group = element.getGroupSymbol();
-            List<Object> elements = groupMap.get(group);
-            if(elements == null) { 
-                elements = new ArrayList<Object>();
-                groupMap.put(group, elements);
-            }
-            elements.add(element.getMetadataID());
-        }    
-             
-        // Walk through each group
-        for (Map.Entry<GroupSymbol, List<Object>> entry : groupMap.entrySet()) {
-            GroupSymbol group = entry.getKey();
-            List<Object> elements = entry.getValue();
-            
-            // Look up keys
-            Collection keys = metadata.getUniqueKeysInGroup(group.getMetadataID());
-            if(keys != null && keys.size() > 0) { 
-                // For each key, get key elements
-                Iterator keyIter = keys.iterator();
-                while(keyIter.hasNext()) { 
-                    List keyElements = metadata.getElementIDsInKey(keyIter.next());
-                    if(elements.containsAll(keyElements)) {
-                        // Used all elements of the key
-                        return true;
-                    }    
-                }
-            }                                    
-        }
-        
-        return false;    
-    }
-    
-    /**
-     * Get the scaled max ndv for a set of elements.
-     * 
-     * NOTE: this is not a good approximation over unions, joins, grouping, etc.
-     */
-    private static float getNDV(Collection<ElementSymbol> elements, PlanNode current, float cardinality, QueryMetadataInterface metadata) 
-        throws QueryMetadataException, TeiidComponentException {
-        float result = 1;
-        
-    	for (ElementSymbol elementSymbol : elements) {
-            Object elemID = elementSymbol.getMetadataID();
-            float ndv = metadata.getDistinctValues(elemID);
-            if (ndv == UNKNOWN_VALUE) {
-                if (metadata.isVirtualGroup(elementSymbol.getGroupSymbol().getMetadataID()) && !metadata.isProcedure(elementSymbol.getGroupSymbol().getMetadataID())) {
-            		PlanNode sourceNode = FrameUtil.findOriginatingNode(current, new HashSet<GroupSymbol>(Arrays.asList(elementSymbol.getGroupSymbol())));
-            		if (sourceNode != null) {
-	        			SymbolMap symbolMap = (SymbolMap)sourceNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
-	        			//symbolMap will be null for table functions
-	        			if (symbolMap != null) {
-		        			Expression expr = symbolMap.getMappedExpression(elementSymbol);
-		        			ndv = getNDV(ElementCollectorVisitor.getElements(expr, true), sourceNode.getFirstChild(), cardinality, metadata);
-	        			}
-            		}
-            	}
-            	if (ndv == UNKNOWN_VALUE) {
-            		return UNKNOWN_VALUE;
-            	}
-            } else if (cardinality != UNKNOWN_VALUE) {
-            	int groupCardinality = metadata.getCardinality(elementSymbol.getGroupSymbol().getMetadataID());
-            	if (groupCardinality != UNKNOWN_VALUE && groupCardinality > cardinality) {
-        			ndv *= cardinality / Math.max(1, groupCardinality);
-            	}
-            }
-            result = Math.max(result, ndv);
-		}
-        return result;
-    }
-    
-    /**
-     * Get the scaled max nnv for a set of elements.
-     * 
-     * NOTE: assumes that the expression does not allow nulls
-     */
-    private static float getNNV(Collection<ElementSymbol> elements, PlanNode current, float cardinality, QueryMetadataInterface metadata) 
-        throws QueryMetadataException, TeiidComponentException {
-        float result = 0;
-    	for (ElementSymbol elementSymbol : elements) {
-            Object elemID = elementSymbol.getMetadataID();
-            float nnv = metadata.getNullValues(elemID);
-            if (nnv == UNKNOWN_VALUE) {
-            	if (!metadata.elementSupports(elemID, SupportConstants.Element.NULL) 
-            			&& !metadata.elementSupports(elemID, SupportConstants.Element.NULL_UNKNOWN)) {
-            		nnv = 0;
-            	} else if (metadata.isVirtualGroup(elementSymbol.getGroupSymbol().getMetadataID()) && !metadata.isProcedure(elementSymbol.getGroupSymbol().getMetadataID())) {
-            		PlanNode sourceNode = FrameUtil.findOriginatingNode(current, new HashSet<GroupSymbol>(Arrays.asList(elementSymbol.getGroupSymbol())));
-            		if (sourceNode != null) {
-	        			SymbolMap symbolMap = (SymbolMap)sourceNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
-	        			Expression expr = symbolMap.getMappedExpression(elementSymbol);
-	        			nnv = getNNV(ElementCollectorVisitor.getElements(expr, true), sourceNode.getFirstChild(), cardinality, metadata);
-            		}
-            	}
-            	if (nnv == UNKNOWN_VALUE) {
-            		return UNKNOWN_VALUE;
-            	}
-            } else if (cardinality != UNKNOWN_VALUE) {
-            	int groupCardinality = metadata.getCardinality(elementSymbol.getGroupSymbol().getMetadataID());
-            	if (groupCardinality != UNKNOWN_VALUE) {
-            		nnv *= cardinality / Math.max(1, groupCardinality);
-            	}
-            }
-            result = Math.max(result, nnv);
-		}
-        return result;
-    }
-    
-    /**
-     * Computes the cost of a Merge Join
-     */
-    public static float computeCostForJoin(PlanNode leftChildNode, PlanNode rightChildNode, JoinStrategyType joinStrategy, QueryMetadataInterface metadata, CommandContext context) 
-        throws TeiidComponentException, QueryMetadataException {
-        
-        float leftChildCardinality = computeCostForTree(leftChildNode, metadata);
-        float rightChildCardinality = computeCostForTree(rightChildNode, metadata);
-        
-        boolean merge = JoinStrategyType.MERGE.equals(joinStrategy);
-                
-        // If either cardinality is unknown, we return unknown
-        if(leftChildCardinality == UNKNOWN_VALUE || rightChildCardinality == UNKNOWN_VALUE) {
-            return UNKNOWN_VALUE;
-        }
-        
-        float numberComparisons = merge?(leftChildCardinality + rightChildCardinality):(leftChildCardinality * rightChildCardinality);
-        
-        float connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
-        if(context != null) {
-            connectorBatchSize = context.getConnectorBatchSize(); 
-        }
-        
-        float totalReadTime = (leftChildCardinality + rightChildCardinality) * readTime;
-        float totalCompareTime = numberComparisons * compareTime;
-        float totalProcMoreRequestLeftTime = (float)Math.floor(leftChildCardinality/connectorBatchSize)*procMoreRequestTime;
-        float totalProcMoreRequestRightTime = (float)Math.floor(rightChildCardinality/connectorBatchSize)*procMoreRequestTime;
-        
-        float cost = (totalReadTime+
-                                           totalCompareTime+
-                                           totalProcMoreRequestLeftTime+
-                                           totalProcMoreRequestRightTime);
-        
-        if (merge) {
-            cost += (leftChildCardinality*safeLog(leftChildCardinality) + rightChildCardinality*safeLog(rightChildCardinality)) * readTime;
-        }
-        
-        if (isPhysicalSource(rightChildNode)) {
-            cost += procNewRequestTime;
-        }
-        if (isPhysicalSource(leftChildNode)) {
-            cost += procNewRequestTime;
-        }
-        return cost;
-    }
-
-    private static float safeLog(float x) {
-        return (float)Math.max(1, Math.log(x));
-    }
-    
-    /**
-     * Computes the cost of a Dependent Join
-     * 
-     * The worst possible cost will arise from a high independent ndv (many dependent sets) and a low dependent ndv (possibly many matches per set)
-     * 
-     * This logic uses the same assumption as criteria in that ndv is used as a divisor of cardinality. 
-     * 
-     */
-    public static float computeCostForDepJoin(PlanNode joinNode, boolean leftIndependent, JoinStrategyType joinStrategy, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, CommandContext context) 
-        throws TeiidComponentException, QueryMetadataException {
-        
-        PlanNode independentNode = leftIndependent?joinNode.getFirstChild():joinNode.getLastChild();
-        PlanNode dependentNode = leftIndependent?joinNode.getLastChild():joinNode.getFirstChild();
-        
-        List independentExpressions = (List)(leftIndependent?joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS):joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS));
-        List dependentExpressions = (List)(leftIndependent?joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS):joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS));
-        
-        // compute the cost for both trees, if we don't come up with a valid cost for both we have to return unknown
-        float independentCardinality = computeCostForTree(independentNode, metadata);
-        float dependentCardinality = computeCostForTree(dependentNode, metadata);
-        
-        float indSymbolNDV = getNDV(independentNode, independentExpressions, metadata, independentCardinality, true);
-        float depSymbolNDV = getNDV(dependentNode, dependentExpressions, metadata, dependentCardinality, false);
-        
-        //If either cardinality is unknown, we return unknown
-        if(indSymbolNDV == UNKNOWN_VALUE || depSymbolNDV == UNKNOWN_VALUE || independentCardinality == UNKNOWN_VALUE || dependentCardinality == UNKNOWN_VALUE) {
-            return UNKNOWN_VALUE;
-        }
-
-        float connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
-        float processorBatchSize = BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE;
-        if(context != null) {
-            connectorBatchSize = context.getConnectorBatchSize();
-            processorBatchSize = context.getProcessorBatchSize();
-        }
-        
-        float setCriteriaBatchSize = indSymbolNDV;
-        
-        PlanNode node = FrameUtil.findJoinSourceNode(dependentNode);
-        
-        while (node != null && node.getType() != NodeConstants.Types.ACCESS) {
-            if (node.getType() == NodeConstants.Types.JOIN || node.getType() == NodeConstants.Types.SET_OP) {
-                node = null;
-                break;
-            }
-            node = node.getFirstChild();
-        }
-        
-        if (node != null) {
-            setCriteriaBatchSize = CapabilitiesUtil.getMaxInCriteriaSize(RuleRaiseAccess.getModelIDFromAccess(node, metadata), metadata, capFinder);
-            if (setCriteriaBatchSize < 1) {
-                setCriteriaBatchSize = indSymbolNDV;
-            }
-        } else {
-            //don't bother making a virtual join dependent if they are likely to be large
-            if (indSymbolNDV > Math.min(processorBatchSize, setCriteriaBatchSize)) {
-                return UNKNOWN_VALUE;
-            }
-        }
-        
-        independentNode.setProperty(NodeConstants.Info.EST_SET_SIZE, new Float(indSymbolNDV));
-        
-        //for non-partitioned joins the cardinality of the dependentaccess should never be greater than the dependent cardinality
-        //TODO: when partitioned joins are implemented, this logic will need updated
-        float dependentAccessCardinality = Math.min(dependentCardinality, dependentCardinality * indSymbolNDV / depSymbolNDV);
-        
-        boolean merge = false;
-        if (JoinStrategyType.MERGE.equals(joinStrategy)) {
-            merge = true;
-        } else if (!JoinStrategyType.NESTED_LOOP.equals(joinStrategy)) {
-            return UNKNOWN_VALUE;
-        }
-        
-        dependentNode.setProperty(NodeConstants.Info.EST_DEP_CARDINALITY, new Float(dependentAccessCardinality));
-        
-        float numberComparisons = merge?(independentCardinality + dependentAccessCardinality):(independentCardinality * dependentAccessCardinality);
-        
-        //account for sorting
-        float totalLoadDataTime = independentCardinality * safeLog(independentCardinality) * readTime;
-        if (merge) {
-            totalLoadDataTime += dependentAccessCardinality * safeLog(dependentAccessCardinality) * readTime;
-        }
-        
-        //the independentCardinality is doubled to account for the dependent setup time, which re-reads the independent values
-        float totalReadTime = (2*independentCardinality + dependentAccessCardinality) * readTime;
-        float totalCompareTime = numberComparisons * compareTime;
-        float totalProcMoreRequestLeftTime = (float)Math.floor(independentCardinality / connectorBatchSize) * procMoreRequestTime;
-        float newDependentQueries = (float)Math.ceil(indSymbolNDV / setCriteriaBatchSize);
-        float totalProcMoreRequestRightTime = Math.max(dependentAccessCardinality / connectorBatchSize - newDependentQueries, 0) * procMoreRequestTime;
-        
-        float cost = (totalLoadDataTime +
-                                           totalReadTime+
-                                           totalCompareTime+
-                                           totalProcMoreRequestLeftTime+
-                                           totalProcMoreRequestRightTime);
-       
-        if (isPhysicalSource(independentNode)) {
-            cost += procNewRequestTime; //independent query latency
-        }
-        /*estimate for dependent query latencies
-         *NOTE: the initial latency estimate can be made significantly larger for queries against large dependent sets,
-         *which is consistent with observed behavior in which criteria-less queries outperform those with in criteria
-         *with 1000 entries.  
-         */        
-        if (isPhysicalSource(dependentNode)) {
-            cost += newDependentQueries * (procNewRequestTime * 
-                            Math.max(safeLog(dependentCardinality) - 10, 1) * 
-                            Math.max(safeLog(Math.min(dependentCardinality, Math.min(setCriteriaBatchSize, indSymbolNDV))) - 2, 1)
-                            ); 
-        }
-        
-        return cost;
-    }
-    
-    private static boolean isPhysicalSource(PlanNode node) {
-        node = FrameUtil.findJoinSourceNode(node);
-        if (node != null) {
-            return node.getType() == NodeConstants.Types.ACCESS;
-        }
-        return false;
-    }
-    
-    private static float getNDV(PlanNode node,
-                                   List expressions,
-                                   QueryMetadataInterface metadata,
-                                   float nodeCardinality, boolean independent) throws QueryMetadataException,
-                                                      TeiidComponentException {
-        float result = UNKNOWN_VALUE;
-        for(Iterator iter = expressions.iterator(); iter.hasNext();) {
-            Expression expr = (Expression)iter.next();
-            Collection<ElementSymbol> symbols = ElementCollectorVisitor.getElements(expr, true);
-            
-            float currentSymbolNDV = getNDV(symbols, node, nodeCardinality, metadata);                
-            
-            if(currentSymbolNDV == UNKNOWN_VALUE) { 
-                if (usesKey(symbols, metadata)) {
-                    return nodeCardinality;
-                } 
-                if (independent) {
-                    currentSymbolNDV = nodeCardinality / 2;
-                } else {
-                    currentSymbolNDV = nodeCardinality / 4;
-                }
-            }
-            
-            if(result == UNKNOWN_VALUE || currentSymbolNDV > result) {
-                result = currentSymbolNDV;
-            }
-        }
-        return Math.max(1, Math.min(nodeCardinality, result));
-    }
-    
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,1097 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.optimizer.relational.rules;
+
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.SupportConstants;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants;
+import org.teiid.query.optimizer.relational.plantree.NodeEditor;
+import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
+import org.teiid.query.sql.lang.AbstractSetCriteria;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.NotCriteria;
+import org.teiid.query.sql.lang.PredicateCriteria;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.EvaluatableVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+import org.teiid.query.util.CommandContext;
+
+/** 
+ * @since 4.3
+ */
+public class NewCalculateCostUtil {
+
+    public static final int UNKNOWN_JOIN_SCALING = 20;
+	public static final float UNKNOWN_VALUE = -1;
+    
+    // the following variables are used to hold cost estimates (roughly in milliseconds)
+    private final static float compareTime = .05f; //TODO: a better estimate would be based upon the number of conjuncts
+    private final static float readTime = .001f; //TODO: should come from the connector
+    private final static float procNewRequestTime = 100; //TODO: should come from the connector
+    private final static float procMoreRequestTime = 15; //TODO: should come from the connector
+    
+    /**
+     * Calculate cost of a node and all children, recursively from the bottom up.
+     * @param node
+     * @param metadata
+     * @return Cost computed at the passed node
+     * @throws QueryMetadataException
+     * @throws TeiidComponentException
+     */
+    static float computeCostForTree(PlanNode node, QueryMetadataInterface metadata) 
+        throws QueryMetadataException, TeiidComponentException {
+
+        Float cost = (Float) node.getProperty(NodeConstants.Info.EST_CARDINALITY);
+
+    	// check if already computed
+        if(cost == null) {
+        	for (PlanNode child : node.getChildren()) {
+        		computeCostForTree(child, metadata);
+            }
+            computeNodeCost(node, metadata);
+            cost = (Float) node.getProperty(NodeConstants.Info.EST_CARDINALITY); 
+        }
+        
+        if(cost != null) {
+            return cost.floatValue();
+        } 
+        
+        return UNKNOWN_VALUE;
+    }
+   
+    /**
+     * This method attempts to estimate a cost for each type of node.
+     * @param node
+     * @param metadata
+     * @throws QueryMetadataException
+     * @throws TeiidComponentException
+     */
+    private static void computeNodeCost(PlanNode node, QueryMetadataInterface metadata) 
+        throws QueryMetadataException, TeiidComponentException {
+        
+        switch(node.getType()) {
+            case NodeConstants.Types.SOURCE:
+                estimateSourceNodeCost(node, metadata);
+                break;
+
+            case NodeConstants.Types.SELECT:
+                estimateSelectNodeCost(node, metadata);
+                break;
+                           
+            case NodeConstants.Types.JOIN:
+                estimateJoinNodeCost(node, metadata);
+                break;
+
+            case NodeConstants.Types.DUP_REMOVE:
+                estimateNodeCost(node, FrameUtil.findTopCols(node), metadata);
+                break;
+
+            case NodeConstants.Types.GROUP:
+            	if (!node.hasCollectionProperty(NodeConstants.Info.GROUP_COLS)) {
+            		setCardinalityEstimate(node, 1f);
+            	} else {
+            		estimateNodeCost(node, (List)node.getProperty(NodeConstants.Info.GROUP_COLS), metadata);
+            	}
+                break;
+            case NodeConstants.Types.ACCESS:
+            case NodeConstants.Types.SORT:
+            {
+                //Simply record the cost of the only child
+                PlanNode child = node.getFirstChild();
+                Float childCost = (Float)child.getProperty(NodeConstants.Info.EST_CARDINALITY);
+                setCardinalityEstimate(node, childCost);
+                break;
+            }
+            case NodeConstants.Types.NULL:
+                setCardinalityEstimate(node, 0f);
+                break;
+
+            case NodeConstants.Types.PROJECT:
+            {
+                Float childCost = null;
+                //Simply record the cost of the only child
+                if (node.getChildCount() != 0) {
+                    PlanNode child = node.getFirstChild();
+                    childCost = (Float)child.getProperty(NodeConstants.Info.EST_CARDINALITY);
+                } else {
+                    childCost = 1f;
+                }
+                setCardinalityEstimate(node, childCost);
+                break;
+            }
+            case NodeConstants.Types.SET_OP: 
+            {
+                estimateSetOpCost(node, metadata);
+                break;
+            }
+            case NodeConstants.Types.TUPLE_LIMIT: 
+            {
+                PlanNode child = node.getFirstChild();
+                float childCost = child.getCardinality();
+                
+                Expression offset = (Expression)node.getProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT);
+                Float cost = childCost;
+                
+                if (childCost != UNKNOWN_VALUE && offset instanceof Constant) {
+                    float offsetCost = childCost - ((Number)((Constant)offset).getValue()).floatValue();
+                    cost = new Float((offsetCost < 0) ? 0 : offsetCost);
+                }
+                
+                Expression limit = (Expression)node.getProperty(NodeConstants.Info.MAX_TUPLE_LIMIT);
+                if (limit instanceof Constant) {
+                    float limitCost = ((Number)((Constant)limit).getValue()).floatValue();
+                    if (cost.floatValue() != UNKNOWN_VALUE) {
+                        cost = new Float(Math.min(limitCost, cost.floatValue()));
+                    } else {
+                        cost = new Float(limitCost);
+                    }
+                } 
+                setCardinalityEstimate(node, cost);
+                break;
+            }
+        }
+    }
+
+	private static void estimateSetOpCost(PlanNode node,
+			QueryMetadataInterface metadata) throws QueryMetadataException,
+			TeiidComponentException {
+		float cost = 0;
+		
+		SetQuery.Operation op = (SetQuery.Operation)node.getProperty(NodeConstants.Info.SET_OPERATION);
+
+		float leftCost = (Float)node.getFirstChild().getProperty(NodeConstants.Info.EST_CARDINALITY);
+		float rightCost = (Float)node.getLastChild().getProperty(NodeConstants.Info.EST_CARDINALITY);
+		
+		if (!node.hasBooleanProperty(NodeConstants.Info.USE_ALL)) {
+			leftCost = getDistinctEstimate(node.getFirstChild(), metadata, leftCost);
+			rightCost = getDistinctEstimate(node.getLastChild(), metadata, rightCost);
+		}
+		
+		cost = leftCost;
+		
+		switch (op) {
+		case EXCEPT:
+			if (leftCost != UNKNOWN_VALUE && rightCost != UNKNOWN_VALUE) {
+		    	cost = Math.max(1, leftCost - .5f * rightCost);
+		    }
+			break;
+		case INTERSECT:
+			if (rightCost != UNKNOWN_VALUE) {
+				if (leftCost != UNKNOWN_VALUE) {
+		    		cost = .5f * Math.min(leftCost, rightCost);
+				} else {
+					cost = rightCost;
+				}
+			}
+			break;
+		default: //union
+			if (leftCost != UNKNOWN_VALUE && rightCost != UNKNOWN_VALUE) {
+		        if (!node.hasBooleanProperty(NodeConstants.Info.USE_ALL)) {
+		        	cost = Math.max(leftCost, rightCost) + .5f * Math.min(leftCost, rightCost);
+		        } else {
+		            cost = rightCost + leftCost;
+		        }
+			}
+			break;
+		}
+		
+		setCardinalityEstimate(node, new Float(cost));
+	}
+
+	private static float getDistinctEstimate(PlanNode node,
+			QueryMetadataInterface metadata, float cost)
+			throws QueryMetadataException, TeiidComponentException {
+		PlanNode projectNode = NodeEditor.findNodePreOrder(node, NodeConstants.Types.PROJECT);
+		if (projectNode != null) {
+			cost = getDistinctEstimate(projectNode, (List)projectNode.getProperty(NodeConstants.Info.PROJECT_COLS), metadata, cost);
+		}
+		return cost;
+	}
+
+    private static void setCardinalityEstimate(PlanNode node, Float bestEstimate) {
+        if (bestEstimate == null){
+        	bestEstimate = Float.valueOf(UNKNOWN_VALUE);
+        }
+        node.setProperty(NodeConstants.Info.EST_CARDINALITY, bestEstimate);
+    }
+
+    /**
+     * Method estimateJoinNodeCost.
+     * @param node
+     * @param metadata
+     */
+    private static void estimateJoinNodeCost(PlanNode node, QueryMetadataInterface metadata)
+        throws QueryMetadataException, TeiidComponentException {
+
+        Iterator<PlanNode> children = node.getChildren().iterator();
+        PlanNode child1 = children.next();
+        float childCost1 = child1.getCardinality();
+        PlanNode child2 = children.next();
+        float childCost2 = child2.getCardinality();
+        
+        if (childCost1 == UNKNOWN_VALUE || childCost2 == UNKNOWN_VALUE) {
+        	setCardinalityEstimate(node, null);
+        	return;
+        }
+
+        JoinType joinType = (JoinType)node.getProperty(NodeConstants.Info.JOIN_TYPE);
+        List joinCriteria = (List) node.getProperty(NodeConstants.Info.JOIN_CRITERIA);
+        
+        float baseCost = childCost1 * childCost2;
+
+        if (joinCriteria != null && !joinCriteria.isEmpty()) {
+    		Criteria crit = Criteria.combineCriteria(joinCriteria);
+    		//TODO: we may be able to get a fairly accurate join estimate if the
+    		//unknown side is being joined with a key
+        	baseCost = recursiveEstimateCostOfCriteria(baseCost, node, crit, metadata);
+        }
+        
+        Float cost = null;
+        if (JoinType.JOIN_CROSS.equals(joinType)){
+            cost = new Float(baseCost);
+        } else if (JoinType.JOIN_FULL_OUTER.equals(joinType)) {
+            cost = new Float(Math.max((childCost1+childCost2),baseCost));
+        } else if (JoinType.JOIN_LEFT_OUTER.equals(joinType)) {
+            cost = new Float(Math.max(childCost1,baseCost));
+        } else if (JoinType.JOIN_RIGHT_OUTER.equals(joinType)) {
+            cost = new Float(Math.max(childCost2,baseCost));
+        } else if (JoinType.JOIN_INNER.equals(joinType)) {
+            cost = new Float(baseCost);
+        }
+        
+        setCardinalityEstimate(node, cost);
+    }
+
+    /**
+     * Estimate the cost of a selection.  This is not easy to do without information 
+     * about the value count for each relation attribute.  
+     * @param metadata
+     */
+    private static void estimateSelectNodeCost(PlanNode node, QueryMetadataInterface metadata) 
+        throws QueryMetadataException, TeiidComponentException {
+
+        PlanNode child = node.getFirstChild();
+        float childCost = child.getCardinality();
+        
+        //Get list of conjuncts
+        Criteria selectCriteria = (Criteria)node.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+        float newCost = recursiveEstimateCostOfCriteria(childCost, node, selectCriteria, metadata);
+        setCardinalityEstimate(node, new Float(newCost));
+    }
+
+    /**
+     * For a source node, the cost is basically the cardinality of the source
+     * (if it is known).
+     * @param node
+     * @param metadata
+     * @throws QueryMetadataException
+     * @throws TeiidComponentException
+     */
+    private static void estimateSourceNodeCost(PlanNode node, QueryMetadataInterface metadata) 
+        throws QueryMetadataException, TeiidComponentException {
+        
+        float cost = UNKNOWN_VALUE;
+        if(node.getChildCount() > 0) {
+        	SymbolMap references = (SymbolMap)node.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
+        	//only cost non-correlated TODO: a better estimate for correlated
+        	if (references == null) {
+	            PlanNode child = node.getFirstChild();
+	            cost = child.getCardinality();
+        	}
+        }else {
+            GroupSymbol group = node.getGroups().iterator().next();
+            float cardinality = metadata.getCardinality(group.getMetadataID());
+            if (cardinality <= QueryMetadataInterface.UNKNOWN_CARDINALITY){
+                cardinality = UNKNOWN_VALUE;
+            }
+            cost = cardinality;
+        }
+        
+        setCardinalityEstimate(node, new Float(cost));
+    } 
+    
+    /**
+     * For a Group or Dup Removal node, the cost is basically the smaller of the largest NDV of the 
+     * selected columns and cost of the child node (if it is known).
+     * @param node
+     * @param metadata
+     * @throws QueryMetadataException
+     * @throws TeiidComponentException
+     */
+    private static void estimateNodeCost(PlanNode node, List expressions, QueryMetadataInterface metadata) 
+        throws QueryMetadataException, TeiidComponentException {
+        
+        PlanNode child = node.getFirstChild();
+        float childCost = child.getCardinality();
+        
+        if(childCost == UNKNOWN_VALUE) {
+            setCardinalityEstimate(node, null);
+            return;
+        }
+
+        Float newCost = getDistinctEstimate(node, expressions, metadata, childCost);
+        setCardinalityEstimate(node, newCost);
+    }
+
+    private static Float getDistinctEstimate(PlanNode node,
+                                             List elements,
+                                             QueryMetadataInterface metadata,
+                                             float childCost) throws QueryMetadataException,
+                                                             TeiidComponentException {
+        if(elements == null) {
+            return new Float(childCost);
+        }
+        HashSet<ElementSymbol> elems = new HashSet<ElementSymbol>();
+        ElementCollectorVisitor.getElements(elements, elems);
+        if (usesKey(elements, metadata)) {
+        	return new Float(childCost);
+        }
+        float ndvCost = getNDV(elems, node, childCost, metadata);
+        if(ndvCost == UNKNOWN_VALUE) {
+            ndvCost = childCost;
+        }
+        
+        Float newCost = new Float(Math.min(childCost, ndvCost));
+        return newCost;
+    }
+    
+    static float recursiveEstimateCostOfCriteria(float childCost, PlanNode currentNode, Criteria crit, QueryMetadataInterface metadata)
+        throws QueryMetadataException, TeiidComponentException {
+        
+        float cost = childCost; 
+        if(crit instanceof CompoundCriteria) {
+            CompoundCriteria compCrit = (CompoundCriteria) crit;
+            if (compCrit.getOperator() == CompoundCriteria.OR) {
+                cost = 0;
+            } 
+            if (usesKey(compCrit, metadata)) {
+                return 1;
+            }
+            for (Criteria critPart : compCrit.getCriteria()) {
+                float nextCost = recursiveEstimateCostOfCriteria(childCost, currentNode, critPart, metadata);
+                
+                if(compCrit.getOperator() == CompoundCriteria.AND) {
+                    if (nextCost == UNKNOWN_VALUE) {
+                        continue;
+                    }
+                    if (childCost != UNKNOWN_VALUE) {
+                        cost *= nextCost/childCost;
+                    } else {
+                        if (cost == UNKNOWN_VALUE) {
+                            cost = nextCost;
+                        } else {
+                            cost = Math.min(cost, nextCost);
+                        }
+                    }
+                    if (cost <= 1) {
+                        return 1;
+                    }
+                } else {
+                    if (nextCost == UNKNOWN_VALUE) {
+                        return childCost;
+                    } 
+                    //this assumes that all disjuncts are completely disjoint
+                    cost += nextCost;
+                    if (childCost != UNKNOWN_VALUE) {
+                        cost = Math.min(cost, childCost);
+                    }
+                }
+            }
+            if (cost == UNKNOWN_VALUE) {
+                return childCost;
+            }
+        } else if(crit instanceof NotCriteria){
+            if (childCost == UNKNOWN_VALUE) {
+                return UNKNOWN_VALUE;
+            }
+            float nextCost = recursiveEstimateCostOfCriteria(childCost, currentNode, ((NotCriteria)crit).getCriteria(), metadata);
+            if (nextCost == UNKNOWN_VALUE){
+                return childCost;
+            }   
+            cost -= nextCost;
+        } else {
+            cost = estimatePredicateCost(childCost, currentNode, (PredicateCriteria) crit, metadata);
+            
+            if (cost == UNKNOWN_VALUE) {
+                return childCost;
+            }
+        }  
+        
+        cost = Math.max(cost, 1);
+        
+        return cost;
+    }
+    
+    /** 
+     * This method is a helper to examine whether a compound criteria covers
+     * a compound key.  A "valid" criteria is 
+     * 1) a predicate criteria
+     *   1a) not negated
+     *   1b) with an equality operator if it is a compare criteria
+     * b) or a compound criteria containing valid criteria and an "AND" operator 
+     * @param criteria
+     * @param elements Collection to collect ElementSymbols in
+     * @since 4.2
+     */
+    private static void collectElementsOfValidCriteria(Criteria criteria, Collection<ElementSymbol> elements) {
+       
+        if(criteria instanceof CompoundCriteria) {
+            CompoundCriteria compCrit = (CompoundCriteria) criteria;
+            Iterator<Criteria> iter = compCrit.getCriteria().iterator();
+            boolean first = true;
+            Collection<ElementSymbol> savedElements = elements;
+            if(compCrit.getOperator() == CompoundCriteria.OR) {
+            	elements = new HashSet<ElementSymbol>();
+            }
+            while(iter.hasNext()) { 
+            	if(compCrit.getOperator() == CompoundCriteria.AND || first) {
+            		collectElementsOfValidCriteria(iter.next(), elements);
+            		first = false;
+            	} else {
+            		HashSet<ElementSymbol> other = new HashSet<ElementSymbol>();
+            		collectElementsOfValidCriteria(iter.next(), other);
+            		elements.retainAll(other);
+            	}
+            }
+            if (compCrit.getOperator() == CompoundCriteria.OR) {
+            	savedElements.addAll(elements);
+            }
+        } else if(criteria instanceof CompareCriteria) {
+            CompareCriteria compCrit = (CompareCriteria)criteria;
+            if (compCrit.getOperator() == CompareCriteria.EQ){
+                ElementCollectorVisitor.getElements(compCrit, elements);
+            }                 
+        } else if(criteria instanceof MatchCriteria) {
+            MatchCriteria matchCriteria = (MatchCriteria)criteria;
+            if (!matchCriteria.isNegated()) {
+                ElementCollectorVisitor.getElements(matchCriteria, elements);
+            }
+
+        } else if(criteria instanceof AbstractSetCriteria) {
+            AbstractSetCriteria setCriteria = (AbstractSetCriteria)criteria;
+            if (!setCriteria.isNegated()) {
+                ElementCollectorVisitor.getElements(setCriteria.getExpression(), elements);
+            }
+        } else if(criteria instanceof IsNullCriteria) {
+            IsNullCriteria isNullCriteria = (IsNullCriteria)criteria;
+            if (!isNullCriteria.isNegated()) {
+                ElementCollectorVisitor.getElements(isNullCriteria.getExpression(), elements);
+            }
+        }        
+    }
+    
+    /** 
+     * @param childCost
+     * @param predicateCriteria
+     * @param metadata
+     * @return
+     * @since 4.3
+     */
+    private static float estimatePredicateCost(float childCost, PlanNode currentNode, PredicateCriteria predicateCriteria, QueryMetadataInterface metadata)
+        throws QueryMetadataException, TeiidComponentException {
+        
+        Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(predicateCriteria, true);
+        
+        Collection<GroupSymbol> groups = GroupsUsedByElementsVisitor.getGroups(elements);
+        boolean multiGroup = groups.size() > 1;
+        
+        float cost = childCost;
+        float ndv = getNDV(elements, currentNode, childCost, metadata);
+        
+        boolean unknownChildCost = childCost == UNKNOWN_VALUE;
+        boolean usesKey = usesKey(elements, metadata);
+        
+        if (childCost == UNKNOWN_VALUE) {
+            childCost = 1;
+        }
+
+        if (ndv == UNKNOWN_VALUE) {
+            ndv = 3;
+            if (multiGroup) {
+                if (usesKey) {
+                    ndv = (float)Math.ceil(Math.sqrt(childCost));
+                } else {
+                    ndv = (float)Math.ceil(Math.sqrt(childCost)/4);
+                }
+                ndv = Math.max(ndv, 1);
+            } else if (usesKey) {
+                ndv = childCost;
+            }
+        } 
+                
+        boolean isNegatedPredicateCriteria = false;
+        if(predicateCriteria instanceof CompareCriteria) {
+            CompareCriteria compCrit = (CompareCriteria) predicateCriteria;
+                        
+            if (compCrit.getOperator() == CompareCriteria.EQ || compCrit.getOperator() == CompareCriteria.NE){
+                if (unknownChildCost && (!usesKey || multiGroup)) {
+                    return UNKNOWN_VALUE;
+                }
+                cost = childCost / ndv;
+                if (compCrit.getOperator() == CompareCriteria.NE) {
+                    isNegatedPredicateCriteria = true;
+                }
+            } else { //GE, LE, GT, LT
+                cost = getCostForComparison(childCost, metadata, compCrit, unknownChildCost);
+            }
+        } else if(predicateCriteria instanceof MatchCriteria) {
+            MatchCriteria matchCriteria = (MatchCriteria)predicateCriteria;
+            if (unknownChildCost) {
+                return UNKNOWN_VALUE;
+            }
+            cost = estimateMatchCost(childCost, ndv, matchCriteria);
+            
+            isNegatedPredicateCriteria = matchCriteria.isNegated();
+
+        } else if(predicateCriteria instanceof SetCriteria) {
+            SetCriteria setCriteria = (SetCriteria) predicateCriteria;
+            if (unknownChildCost) {
+                return UNKNOWN_VALUE;
+            }
+            cost = childCost * setCriteria.getNumberOfValues() / ndv;
+            
+            isNegatedPredicateCriteria = setCriteria.isNegated();
+            
+        } else if(predicateCriteria instanceof SubquerySetCriteria) {
+            SubquerySetCriteria setCriteria = (SubquerySetCriteria) predicateCriteria;
+            
+            // TODO - use inner ProcessorPlan cardinality estimates 
+            // to determine the estimated number of values
+            if (unknownChildCost) {
+                return UNKNOWN_VALUE;
+            }
+            cost = childCost / 3;
+            
+            isNegatedPredicateCriteria = setCriteria.isNegated();
+
+        } else if(predicateCriteria instanceof IsNullCriteria) {
+            IsNullCriteria isNullCriteria = (IsNullCriteria)predicateCriteria;
+
+            float nnv = getNNV(elements, currentNode, childCost, metadata);
+            if (nnv == UNKNOWN_VALUE) {
+            	if (unknownChildCost) {
+            		return UNKNOWN_VALUE;
+            	}
+                cost = childCost / ndv;
+            } else {
+                cost = nnv;
+            }
+            
+            isNegatedPredicateCriteria = isNullCriteria.isNegated();
+        }
+
+        if (cost == UNKNOWN_VALUE) {
+            return UNKNOWN_VALUE;
+        }
+        
+        if (cost > childCost) {
+            cost = childCost;
+        }
+        
+        if (isNegatedPredicateCriteria) {
+            // estimate for NOT in the predicate
+            cost = (cost != UNKNOWN_VALUE)
+                    ? Math.max( childCost - cost, 1)
+                    : UNKNOWN_VALUE;
+        }
+                
+        return cost;
+    }
+
+    /** 
+     * TODO: does not check for escape char
+     * or if it will contain single match chars
+     */
+    private static float estimateMatchCost(float childCost,
+                                           float ndv,
+                                           MatchCriteria criteria) {
+        Expression matchExpression = criteria.getRightExpression();
+        if(matchExpression instanceof Constant && ((Constant)matchExpression).getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
+            String compareValue = (String) ((Constant)matchExpression).getValue();
+            if(compareValue != null && compareValue.indexOf('%') < 0) {
+            	return (childCost / 2) * (1 / 3f  + 1 / ndv); //without knowing length constraints we'll make an average guess
+            }
+        } else if (EvaluatableVisitor.willBecomeConstant(criteria.getLeftExpression())) {
+            return childCost / ndv;
+        }
+        return childCost / 3;
+    }
+
+    private static float getCostForComparison(float childCost,
+                                              QueryMetadataInterface metadata,
+                                              CompareCriteria compCrit, boolean unknownChildCost) throws TeiidComponentException,
+                                                                       QueryMetadataException {
+        if (!(compCrit.getLeftExpression() instanceof ElementSymbol) || !(compCrit.getRightExpression() instanceof Constant)) {
+            if (unknownChildCost) {
+                return UNKNOWN_VALUE;
+            }
+            return childCost/3;
+        }
+        ElementSymbol element = (ElementSymbol)compCrit.getLeftExpression();
+        Class dataType = compCrit.getRightExpression().getType();
+    
+        String max = (String)metadata.getMaximumValue(element.getMetadataID());
+        String min = (String)metadata.getMinimumValue(element.getMetadataID());
+        if(max == null || min == null) {
+            if (unknownChildCost) {
+                return UNKNOWN_VALUE;
+            }
+            return childCost/3;
+        } 
+        float cost = childCost;
+        try{
+            float maxValue = 0;
+            float minValue = 0;
+
+            Constant value = (Constant)compCrit.getRightExpression();
+            float compareValue = 0;
+        	// Case 6257 - handling added for time and date.  If the max/min values are not
+            // in the expected format, NumberFormatException is thrown and reverts to default costing.
+            if(dataType.equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
+                compareValue = ((Timestamp)value.getValue()).getTime();
+                maxValue = Timestamp.valueOf(max).getTime();
+                minValue = Timestamp.valueOf(min).getTime();
+            } else if(dataType.equals(DataTypeManager.DefaultDataClasses.TIME)) {
+                compareValue = ((Time)value.getValue()).getTime();
+                maxValue = Time.valueOf(max).getTime();
+                minValue = Time.valueOf(min).getTime();
+            // (For date, our costing sets the max and min values using timestamp format)
+            } else if(dataType.equals(DataTypeManager.DefaultDataClasses.DATE)) {
+                compareValue = ((Date)value.getValue()).getTime();
+                maxValue = Timestamp.valueOf(max).getTime();
+                minValue = Timestamp.valueOf(min).getTime();
+            } else {
+            	if(!Number.class.isAssignableFrom(dataType)) {
+                    if (unknownChildCost) {
+                        return UNKNOWN_VALUE;
+                    }
+                    return childCost/3;
+                }
+                compareValue = ((Number)value.getValue()).floatValue();
+                maxValue = Integer.parseInt(max);
+                minValue = Integer.parseInt(min);
+            }
+            float range = Math.max(maxValue - minValue, 1);
+            
+            float costMultiple = 1;
+            
+            if(compCrit.getOperator() == CompareCriteria.GT || compCrit.getOperator() == CompareCriteria.GE) {
+            	costMultiple = (maxValue - compareValue)/range;
+                if (compareValue < 0 && maxValue < 0) {
+                	costMultiple = (1 - costMultiple);
+                }
+            } else if(compCrit.getOperator() == CompareCriteria.LT || compCrit.getOperator() == CompareCriteria.LE) {
+            	costMultiple = (compareValue - minValue)/range;
+                if (compareValue < 0 && minValue < 0) {
+                	costMultiple = (1 - costMultiple);
+                }
+            }
+            if (costMultiple > 1) {
+            	costMultiple = 1;
+            } else if (costMultiple < 0) {
+            	costMultiple = 0;
+            }
+            cost = childCost * costMultiple;
+        }catch(IllegalArgumentException e) {
+            LogManager.logWarning(LogConstants.CTX_QUERY_PLANNER, e, QueryPlugin.Util.getString("NewCalculateCostUtil.badCost")); //$NON-NLS-1$
+            // If we were unable to parse the timestamp we will revert to the divide by three estimate
+            if (unknownChildCost) {
+                return UNKNOWN_VALUE;
+            }
+            cost = childCost/3;
+        }
+        return cost;
+    }
+    
+    static boolean usesKey(PlanNode planNode, Collection<? extends SingleElementSymbol> allElements, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
+    	return NodeEditor.findAllNodes(planNode, NodeConstants.Types.SOURCE, NodeConstants.Types.JOIN | NodeConstants.Types.SET_OP).size() == 1
+    	&& usesKey(allElements, metadata);
+    }
+    
+    public static boolean usesKey(Criteria crit, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
+        HashSet<ElementSymbol> elements = new HashSet<ElementSymbol>();
+        collectElementsOfValidCriteria(crit, elements);
+        return usesKey(elements, metadata);
+    }
+    
+    /**
+     * TODO: this uses key check is not really accurate, it doesn't take into consideration where 
+     * we are in the plan.
+     * if a key column is used after a non 1-1 join or a union all, then it may be non-unique.
+     */
+    private static boolean usesKey(Collection<? extends SingleElementSymbol> allElements, QueryMetadataInterface metadata)
+        throws QueryMetadataException, TeiidComponentException {
+    
+        if(allElements == null || allElements.size() == 0) { 
+            return false;
+        }    
+     
+        // Sort elements into groups
+        Map<GroupSymbol, List<Object>> groupMap = new HashMap<GroupSymbol, List<Object>>();
+        for (SingleElementSymbol ses : allElements) {
+        	if (!(ses instanceof ElementSymbol)) {
+        		continue;
+        	}
+        	ElementSymbol element = (ElementSymbol)ses;
+            GroupSymbol group = element.getGroupSymbol();
+            List<Object> elements = groupMap.get(group);
+            if(elements == null) { 
+                elements = new ArrayList<Object>();
+                groupMap.put(group, elements);
+            }
+            elements.add(element.getMetadataID());
+        }    
+             
+        // Walk through each group
+        for (Map.Entry<GroupSymbol, List<Object>> entry : groupMap.entrySet()) {
+            GroupSymbol group = entry.getKey();
+            List<Object> elements = entry.getValue();
+            
+            // Look up keys
+            Collection keys = metadata.getUniqueKeysInGroup(group.getMetadataID());
+            if(keys != null && keys.size() > 0) { 
+                // For each key, get key elements
+                Iterator keyIter = keys.iterator();
+                while(keyIter.hasNext()) { 
+                    List keyElements = metadata.getElementIDsInKey(keyIter.next());
+                    if(elements.containsAll(keyElements)) {
+                        // Used all elements of the key
+                        return true;
+                    }    
+                }
+            }                                    
+        }
+        
+        return false;    
+    }
+    
+    /**
+     * Get the scaled max ndv for a set of elements.
+     * 
+     * NOTE: this is not a good approximation over unions, joins, grouping, etc.
+     */
+    private static float getNDV(Collection<ElementSymbol> elements, PlanNode current, float cardinality, QueryMetadataInterface metadata) 
+        throws QueryMetadataException, TeiidComponentException {
+        float result = UNKNOWN_VALUE;
+        
+    	for (ElementSymbol elementSymbol : elements) {
+            Object elemID = elementSymbol.getMetadataID();
+            float ndv = metadata.getDistinctValues(elemID);
+            if (ndv == UNKNOWN_VALUE) {
+                if (metadata.isVirtualGroup(elementSymbol.getGroupSymbol().getMetadataID()) && !metadata.isProcedure(elementSymbol.getGroupSymbol().getMetadataID())) {
+            		PlanNode sourceNode = FrameUtil.findOriginatingNode(current, new HashSet<GroupSymbol>(Arrays.asList(elementSymbol.getGroupSymbol())));
+            		if (sourceNode != null) {
+	        			SymbolMap symbolMap = (SymbolMap)sourceNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
+	        			//symbolMap will be null for table functions
+	        			if (symbolMap != null) {
+		        			Expression expr = symbolMap.getMappedExpression(elementSymbol);
+		        			ndv = getNDV(ElementCollectorVisitor.getElements(expr, true), sourceNode.getFirstChild(), cardinality, metadata);
+	        			}
+            		}
+            	}
+            } else if (cardinality != UNKNOWN_VALUE) {
+            	int groupCardinality = metadata.getCardinality(elementSymbol.getGroupSymbol().getMetadataID());
+            	if (groupCardinality != UNKNOWN_VALUE && groupCardinality > cardinality) {
+        			ndv *= cardinality / Math.max(1, groupCardinality);
+            	}
+            }
+            result = Math.max(result, ndv);
+		}
+        return result;
+    }
+    
+    /**
+     * Get the scaled max nnv for a set of elements.
+     * 
+     * NOTE: assumes that the expression does not allow nulls
+     */
+    private static float getNNV(Collection<ElementSymbol> elements, PlanNode current, float cardinality, QueryMetadataInterface metadata) 
+        throws QueryMetadataException, TeiidComponentException {
+        float result = 0;
+    	for (ElementSymbol elementSymbol : elements) {
+            Object elemID = elementSymbol.getMetadataID();
+            float nnv = metadata.getNullValues(elemID);
+            if (nnv == UNKNOWN_VALUE) {
+            	if (!metadata.elementSupports(elemID, SupportConstants.Element.NULL) 
+            			&& !metadata.elementSupports(elemID, SupportConstants.Element.NULL_UNKNOWN)) {
+            		nnv = 0;
+            	} else if (metadata.isVirtualGroup(elementSymbol.getGroupSymbol().getMetadataID()) && !metadata.isProcedure(elementSymbol.getGroupSymbol().getMetadataID())) {
+            		PlanNode sourceNode = FrameUtil.findOriginatingNode(current, new HashSet<GroupSymbol>(Arrays.asList(elementSymbol.getGroupSymbol())));
+            		if (sourceNode != null) {
+	        			SymbolMap symbolMap = (SymbolMap)sourceNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
+	        			Expression expr = symbolMap.getMappedExpression(elementSymbol);
+	        			nnv = getNNV(ElementCollectorVisitor.getElements(expr, true), sourceNode.getFirstChild(), cardinality, metadata);
+            		}
+            	}
+            	if (nnv == UNKNOWN_VALUE) {
+            		return UNKNOWN_VALUE;
+            	}
+            } else if (cardinality != UNKNOWN_VALUE) {
+            	int groupCardinality = metadata.getCardinality(elementSymbol.getGroupSymbol().getMetadataID());
+            	if (groupCardinality != UNKNOWN_VALUE) {
+            		nnv *= cardinality / Math.max(1, groupCardinality);
+            	}
+            }
+            result = Math.max(result, nnv);
+		}
+        return result;
+    }
+    
+    /**
+     * Computes the cost of a Merge Join
+     */
+    public static float computeCostForJoin(PlanNode leftChildNode, PlanNode rightChildNode, JoinStrategyType joinStrategy, QueryMetadataInterface metadata, CommandContext context) 
+        throws TeiidComponentException, QueryMetadataException {
+        
+        float leftChildCardinality = computeCostForTree(leftChildNode, metadata);
+        float rightChildCardinality = computeCostForTree(rightChildNode, metadata);
+        
+        boolean merge = JoinStrategyType.MERGE.equals(joinStrategy);
+                
+        // If either cardinality is unknown, we return unknown
+        if(leftChildCardinality == UNKNOWN_VALUE || rightChildCardinality == UNKNOWN_VALUE) {
+            return UNKNOWN_VALUE;
+        }
+        
+        float numberComparisons = merge?(leftChildCardinality + rightChildCardinality):(leftChildCardinality * rightChildCardinality);
+        
+        float connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
+        if(context != null) {
+            connectorBatchSize = context.getConnectorBatchSize(); 
+        }
+        
+        float totalReadTime = (leftChildCardinality + rightChildCardinality) * readTime;
+        float totalCompareTime = numberComparisons * compareTime;
+        float totalProcMoreRequestLeftTime = (float)Math.floor(leftChildCardinality/connectorBatchSize)*procMoreRequestTime;
+        float totalProcMoreRequestRightTime = (float)Math.floor(rightChildCardinality/connectorBatchSize)*procMoreRequestTime;
+        
+        float cost = (totalReadTime+
+                                           totalCompareTime+
+                                           totalProcMoreRequestLeftTime+
+                                           totalProcMoreRequestRightTime);
+        
+        if (merge) {
+            cost += (leftChildCardinality*safeLog(leftChildCardinality) + rightChildCardinality*safeLog(rightChildCardinality)) * readTime;
+        }
+        
+        if (isPhysicalSource(rightChildNode)) {
+            cost += procNewRequestTime;
+        }
+        if (isPhysicalSource(leftChildNode)) {
+            cost += procNewRequestTime;
+        }
+        return cost;
+    }
+
+    private static float safeLog(float x) {
+        return (float)Math.max(1, Math.log(x));
+    }
+    
+    /**
+     * Computes the cost of a Dependent Join
+     * 
+     * The worst possible cost will arise from a high independent ndv (many dependent sets) and a low dependent ndv (possibly many matches per set)
+     * 
+     * This logic uses the same assumption as criteria in that ndv is used as a divisor of cardinality. 
+     * 
+     */
+    public static float computeCostForDepJoin(PlanNode joinNode, boolean leftIndependent, JoinStrategyType joinStrategy, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, CommandContext context) 
+        throws TeiidComponentException, QueryMetadataException {
+        
+        PlanNode independentNode = leftIndependent?joinNode.getFirstChild():joinNode.getLastChild();
+        PlanNode dependentNode = leftIndependent?joinNode.getLastChild():joinNode.getFirstChild();
+        
+        List independentExpressions = (List)(leftIndependent?joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS):joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS));
+        List dependentExpressions = (List)(leftIndependent?joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS):joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS));
+        
+        // compute the cost for both trees, if we don't come up with a valid cost for both we have to return unknown
+        float independentCardinality = computeCostForTree(independentNode, metadata);
+        float dependentCardinality = computeCostForTree(dependentNode, metadata);
+        
+        float indSymbolNDV = getNDV(independentNode, independentExpressions, metadata, independentCardinality, true);
+        float depSymbolNDV = getNDV(dependentNode, dependentExpressions, metadata, dependentCardinality, false);
+        
+        //If either cardinality is unknown, we return unknown
+        if(indSymbolNDV == UNKNOWN_VALUE || depSymbolNDV == UNKNOWN_VALUE || independentCardinality == UNKNOWN_VALUE || dependentCardinality == UNKNOWN_VALUE) {
+            return UNKNOWN_VALUE;
+        }
+
+        float connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
+        float processorBatchSize = BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE;
+        if(context != null) {
+            connectorBatchSize = context.getConnectorBatchSize();
+            processorBatchSize = context.getProcessorBatchSize();
+        }
+        
+        float setCriteriaBatchSize = indSymbolNDV;
+        
+        PlanNode node = FrameUtil.findJoinSourceNode(dependentNode);
+        
+        while (node != null && node.getType() != NodeConstants.Types.ACCESS) {
+            if (node.getType() == NodeConstants.Types.JOIN || node.getType() == NodeConstants.Types.SET_OP) {
+                node = null;
+                break;
+            }
+            node = node.getFirstChild();
+        }
+        
+        if (node != null) {
+            setCriteriaBatchSize = CapabilitiesUtil.getMaxInCriteriaSize(RuleRaiseAccess.getModelIDFromAccess(node, metadata), metadata, capFinder);
+            if (setCriteriaBatchSize < 1) {
+                setCriteriaBatchSize = indSymbolNDV;
+            }
+        } else {
+            //don't bother making a virtual join dependent if they are likely to be large
+            if (indSymbolNDV > Math.min(processorBatchSize, setCriteriaBatchSize)) {
+                return UNKNOWN_VALUE;
+            }
+        }
+        
+        independentNode.setProperty(NodeConstants.Info.EST_SET_SIZE, new Float(indSymbolNDV));
+        
+        //for non-partitioned joins the cardinality of the dependentaccess should never be greater than the dependent cardinality
+        //TODO: when partitioned joins are implemented, this logic will need updated
+        float dependentAccessCardinality = Math.min(dependentCardinality, dependentCardinality * indSymbolNDV / depSymbolNDV);
+        
+        boolean merge = false;
+        if (JoinStrategyType.MERGE.equals(joinStrategy)) {
+            merge = true;
+        } else if (!JoinStrategyType.NESTED_LOOP.equals(joinStrategy)) {
+            return UNKNOWN_VALUE;
+        }
+        
+        dependentNode.setProperty(NodeConstants.Info.EST_DEP_CARDINALITY, new Float(dependentAccessCardinality));
+        
+        float numberComparisons = merge?(independentCardinality + dependentAccessCardinality):(independentCardinality * dependentAccessCardinality);
+        
+        //account for sorting
+        float totalLoadDataTime = independentCardinality * safeLog(independentCardinality) * readTime;
+        if (merge) {
+            totalLoadDataTime += dependentAccessCardinality * safeLog(dependentAccessCardinality) * readTime;
+        }
+        
+        //the independentCardinality is doubled to account for the dependent setup time, which re-reads the independent values
+        float totalReadTime = (2*independentCardinality + dependentAccessCardinality) * readTime;
+        float totalCompareTime = numberComparisons * compareTime;
+        float totalProcMoreRequestLeftTime = (float)Math.floor(independentCardinality / connectorBatchSize) * procMoreRequestTime;
+        float newDependentQueries = (float)Math.ceil(indSymbolNDV / setCriteriaBatchSize);
+        float totalProcMoreRequestRightTime = Math.max(dependentAccessCardinality / connectorBatchSize - newDependentQueries, 0) * procMoreRequestTime;
+        
+        float cost = (totalLoadDataTime +
+                                           totalReadTime+
+                                           totalCompareTime+
+                                           totalProcMoreRequestLeftTime+
+                                           totalProcMoreRequestRightTime);
+       
+        if (isPhysicalSource(independentNode)) {
+            cost += procNewRequestTime; //independent query latency
+        }
+        /*estimate for dependent query latencies
+         *NOTE: the initial latency estimate can be made significantly larger for queries against large dependent sets,
+         *which is consistent with observed behavior in which criteria-less queries outperform those with in criteria
+         *with 1000 entries.  
+         */        
+        if (isPhysicalSource(dependentNode)) {
+            cost += newDependentQueries * (procNewRequestTime * 
+                            Math.max(safeLog(dependentCardinality) - 10, 1) * 
+                            Math.max(safeLog(Math.min(dependentCardinality, Math.min(setCriteriaBatchSize, indSymbolNDV))) - 2, 1)
+                            ); 
+        }
+        
+        return cost;
+    }
+    
+    private static boolean isPhysicalSource(PlanNode node) {
+        node = FrameUtil.findJoinSourceNode(node);
+        if (node != null) {
+            return node.getType() == NodeConstants.Types.ACCESS;
+        }
+        return false;
+    }
+    
+    private static float getNDV(PlanNode node,
+                                   List expressions,
+                                   QueryMetadataInterface metadata,
+                                   float nodeCardinality, boolean independent) throws QueryMetadataException,
+                                                      TeiidComponentException {
+        float result = UNKNOWN_VALUE;
+        for(Iterator iter = expressions.iterator(); iter.hasNext();) {
+            Expression expr = (Expression)iter.next();
+            Collection<ElementSymbol> symbols = ElementCollectorVisitor.getElements(expr, true);
+            
+            float currentSymbolNDV = getNDV(symbols, node, nodeCardinality, metadata);                
+            
+            if(currentSymbolNDV == UNKNOWN_VALUE) { 
+                if (usesKey(symbols, metadata)) {
+                    return nodeCardinality;
+                } 
+                if (independent) {
+                    currentSymbolNDV = nodeCardinality / 2;
+                } else {
+                    currentSymbolNDV = nodeCardinality / 4;
+                }
+            }
+            
+            if(result == UNKNOWN_VALUE || currentSymbolNDV > result) {
+                result = currentSymbolNDV;
+            }
+        }
+        return Math.max(1, Math.min(nodeCardinality, result));
+    }
+    
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,840 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.language.SortSpecification.NullOrdering;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.SupportConstants;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.optimizer.relational.OptimizerRule;
-import org.teiid.query.optimizer.relational.RuleStack;
-import org.teiid.query.optimizer.relational.plantree.NodeConstants;
-import org.teiid.query.optimizer.relational.plantree.NodeEditor;
-import org.teiid.query.optimizer.relational.plantree.NodeFactory;
-import org.teiid.query.optimizer.relational.plantree.PlanNode;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.OrderByItem;
-import org.teiid.query.sql.lang.SetQuery.Operation;
-import org.teiid.query.sql.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.util.CommandContext;
-import org.teiid.translator.ExecutionFactory.NullOrder;
-import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
-
-
-public final class RuleRaiseAccess implements OptimizerRule {
-
-	public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
-		throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
-        boolean afterJoinPlanning = !rules.contains(RuleConstants.PLAN_JOINS);
-        
-        // Loop until nothing has been raised - plan is then stable and can be returned
-        boolean raisedNode = true;
-        while(raisedNode) {
-            raisedNode = false;
-
-            for (PlanNode accessNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.ACCESS)) {
-                PlanNode newRoot = raiseAccessNode(plan, accessNode, metadata, capFinder, afterJoinPlanning, analysisRecord);
-                if(newRoot != null) {
-                    raisedNode = true;
-                    plan = newRoot;
-                }
-            }            
-        }
-        
-        return plan;
-	}
-    
-    /**
-     * @return null if nothing changed, and a new plan root if something changed
-     */
-    static PlanNode raiseAccessNode(PlanNode rootNode, PlanNode accessNode, QueryMetadataInterface metadata, 
-    		CapabilitiesFinder capFinder, boolean afterJoinPlanning, AnalysisRecord record) 
-    throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-        
-        PlanNode parentNode = accessNode.getParent();
-        if(parentNode == null) {
-            // Nothing to raise over
-            return null;
-        }
-        Object modelID = getModelIDFromAccess(accessNode, metadata);
-        if(modelID == null) {
-            return null;
-        }
-        
-        switch(parentNode.getType()) {
-            case NodeConstants.Types.JOIN:
-            {
-                modelID = canRaiseOverJoin(modelID, parentNode, metadata, capFinder, afterJoinPlanning, record);
-                if(modelID != null) {
-                    raiseAccessOverJoin(parentNode, modelID, true);                    
-                    return rootNode;
-                }
-                return null;
-            }            
-            case NodeConstants.Types.PROJECT:
-            {         
-                // Check that the PROJECT contains only functions that can be pushed                               
-                List projectCols = (List) parentNode.getProperty(NodeConstants.Info.PROJECT_COLS);
-                
-                for (int i = 0; i < projectCols.size(); i++) {
-                    SingleElementSymbol symbol = (SingleElementSymbol)projectCols.get(i);
-                    if(! canPushSymbol(symbol, true, modelID, metadata, capFinder, record)) {
-                        return null;
-                    } 
-                }
-                
-                /*
-                 * TODO: this creates an extraneous project node in many circumstances.
-                 * However we don't actually support project in this case, so allowing it to be pushed
-                 * causes problems with stored procedures and the assumptions made for proc/relational
-                 * planning. 
-                 */
-                if (FrameUtil.isProcedure(parentNode)) {
-                	return null;
-                }
-                                
-                return performRaise(rootNode, accessNode, parentNode);                
-            }
-            case NodeConstants.Types.DUP_REMOVE:
-            {     
-                // If model supports the support constant parameter, then move access node
-                if(!CapabilitiesUtil.supportsSelectDistinct(modelID, metadata, capFinder)) {
-                	recordDebug("cannot push dupremove, since distinct is not supported by source", parentNode, record); //$NON-NLS-1$
-                	return null;
-                }
-                
-                //TODO: this check is too specific the columns could be used in expressions that are comparable
-                if (!CapabilitiesUtil.checkElementsAreSearchable((List)NodeEditor.findNodePreOrder(parentNode, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS), metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
-                	recordDebug("cannot push dupremove, since not all columns are comparable at the source", parentNode, record); //$NON-NLS-1$
-                	return null;
-                }
-                
-                return performRaise(rootNode, accessNode, parentNode);
-            }
-            case NodeConstants.Types.SORT:
-            {         
-                if (canRaiseOverSort(accessNode, metadata, capFinder, parentNode, record)) {
-                    return performRaise(rootNode, accessNode, parentNode);
-                }
-                return null;
-            }            
-            case NodeConstants.Types.GROUP:            
-            {                
-                Set<AggregateSymbol> aggregates = RulePushAggregates.collectAggregates(parentNode);
-                if (canRaiseOverGroupBy(parentNode, accessNode, aggregates, metadata, capFinder, record)) {
-                    return performRaise(rootNode, accessNode, parentNode);
-                }
-                return null;
-            } 
-            case NodeConstants.Types.SET_OP:
-            	if (!canRaiseOverSetQuery(parentNode, metadata, capFinder)) {
-            		return null;
-            	}
-
-            	for (PlanNode node : new ArrayList<PlanNode>(parentNode.getChildren())) {
-            		if (node == accessNode) {
-            			continue;
-            		}
-        			NodeEditor.removeChildNode(parentNode, node);
-            	}
-            	accessNode.getGroups().clear();
-                return performRaise(rootNode, accessNode, parentNode);
-            case NodeConstants.Types.SELECT:            
-            {
-            	if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET)) {
-            		return null;
-            	}
-            	if (canRaiseOverSelect(accessNode, metadata, capFinder, parentNode, record)) {
-                    RulePushSelectCriteria.satisfyAccessPatterns(parentNode, accessNode);
-                    return performRaise(rootNode, accessNode, parentNode);                      
-            	}
-            	//determine if we should push the select back up
-            	if (parentNode.getParent() == null) {
-            		return null;
-            	}
-        		PlanNode selectRoot = parentNode;
-        		while (selectRoot.getParent() != null && selectRoot.getParent().getType() == NodeConstants.Types.SELECT) {
-        			selectRoot = selectRoot.getParent();
-        		}
-        		if (selectRoot.getParent() == null || (selectRoot.getParent().getType() & (NodeConstants.Types.PROJECT|NodeConstants.Types.GROUP)) == selectRoot.getParent().getType()) {
-        			return null;
-        		}
-    			PlanNode grandParent = selectRoot.getParent();
-    			boolean isLeft = false;
-				isLeft = grandParent.getFirstChild() == selectRoot;
-				if (grandParent.getType() == NodeConstants.Types.JOIN) {
-					JoinType jt = (JoinType)grandParent.getProperty(NodeConstants.Info.JOIN_TYPE);
-					if (jt == JoinType.JOIN_FULL_OUTER || (jt == JoinType.JOIN_LEFT_OUTER && !isLeft)) {
-						return null;
-					}
-				}
-				grandParent.removeChild(selectRoot);
-				if (isLeft) {
-					grandParent.addFirstChild(accessNode);
-				} else {
-					grandParent.addLastChild(accessNode);
-				}
-    			PlanNode newParent = grandParent.getParent();
-				//TODO: use costing or heuristics instead of always raising
-    			PlanNode newRoot = raiseAccessNode(rootNode, accessNode, metadata, capFinder, afterJoinPlanning, record);
-    			if (newRoot == null) {
-					//return the tree to its original state
-    				parentNode.addFirstChild(accessNode);
-    				if (isLeft) {
-    					grandParent.addFirstChild(selectRoot);
-    				} else {
-    					grandParent.addLastChild(selectRoot);
-    				}
-    			} else {
-    				//attach the select nodes above the access node
-    				accessNode = grandParent.getParent();
-					if (newParent != null) {
-    					isLeft = newParent.getFirstChild() == accessNode;
-    					if (isLeft) {
-    						newParent.addFirstChild(selectRoot);
-    					} else {
-    						newParent.addLastChild(selectRoot);
-    					}
-    				} else {
-    					newRoot = selectRoot;
-    				}
-					parentNode.addFirstChild(accessNode);
-    				return newRoot;
-    			}
-                return null;
-            }   
-            case NodeConstants.Types.SOURCE:
-            {
-                //if a source has access patterns that are unsatisfied, then the raise cannot occur
-                if (parentNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
-                    return null;
-                }
-                
-                SymbolMap references = (SymbolMap)parentNode.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
-                if (references != null) {
-                	return null;
-                }
-                
-                //raise only if there is no intervening project into
-                PlanNode parentProject = NodeEditor.findParent(parentNode, NodeConstants.Types.PROJECT);
-                GroupSymbol intoGroup = (GroupSymbol)parentProject.getProperty(NodeConstants.Info.INTO_GROUP); 
-                if (intoGroup != null && parentProject.getParent() == null) {
-                	if (CapabilitiesUtil.supports(Capability.INSERT_WITH_QUERYEXPRESSION, modelID, metadata, capFinder) && CapabilitiesUtil.isSameConnector(modelID, metadata.getModelID(intoGroup.getMetadataID()), metadata, capFinder)) {
-                    	rootNode = performRaise(rootNode, accessNode, parentNode);
-                    	return performRaise(rootNode, accessNode, parentProject);
-                	}
-                	return null;
-                } else if (!CapabilitiesUtil.supportsInlineView(modelID, metadata, capFinder)) {
-                	return null;
-                }
-
-                //is there another query that will be used with this source
-                if (FrameUtil.getNonQueryCommand(accessNode) != null || FrameUtil.getNestedPlan(accessNode) != null) {
-                	return null;
-                }
-                                
-                //switch to inline view and change the group on the access to that of the source
-            	parentNode.setProperty(NodeConstants.Info.INLINE_VIEW, Boolean.TRUE);
-            	accessNode.getGroups().clear();
-            	accessNode.addGroups(parentNode.getGroups());
-                RulePlaceAccess.copyDependentHints(parentNode, accessNode);
-            	return performRaise(rootNode, accessNode, parentNode);
-            }
-            case NodeConstants.Types.TUPLE_LIMIT:
-            {
-                return RulePushLimit.raiseAccessOverLimit(rootNode, accessNode, metadata, capFinder, parentNode);
-            }
-            default: 
-            {
-                return null;
-            }                      
-        }        
-    }
-
-    static boolean canRaiseOverGroupBy(PlanNode groupNode,
-                                         PlanNode accessNode,
-                                         Collection<? extends SingleElementSymbol> aggregates,
-                                         QueryMetadataInterface metadata,
-                                         CapabilitiesFinder capFinder, AnalysisRecord record) throws QueryMetadataException,
-                                                        TeiidComponentException {
-        Object modelID = getModelIDFromAccess(accessNode, metadata);
-        if(modelID == null) {
-            return false;
-        }
-        List<SingleElementSymbol> groupCols = (List<SingleElementSymbol>)groupNode.getProperty(NodeConstants.Info.GROUP_COLS);
-        if(!CapabilitiesUtil.supportsAggregates(groupCols, modelID, metadata, capFinder)) {
-        	recordDebug("cannot push group by, since group by is not supported by source", groupNode, record); //$NON-NLS-1$
-            return false;
-        }
-        if (groupCols != null) {
-            for (SingleElementSymbol singleElementSymbol : groupCols) {
-                if (!canPushSymbol(singleElementSymbol, false, modelID, metadata, capFinder, record)) {
-                    return false;
-                }
-            }
-        }
-        if (aggregates != null) {
-            for (SingleElementSymbol aggregateSymbol : aggregates) {
-                if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(aggregateSymbol, modelID, metadata, capFinder, record)) {
-                    return false;
-                }
-            }
-        }
-        return CapabilitiesUtil.checkElementsAreSearchable(groupCols, metadata, SupportConstants.Element.SEARCHABLE_COMPARE);
-    }
-
-	private static void recordDebug(String message, PlanNode node, AnalysisRecord record) {
-		if (record != null && record.recordDebug()) {
-			record.println(message + " " + node.nodeToString()); //$NON-NLS-1$
-		}
-	}
-    
-    static boolean canRaiseOverSort(PlanNode accessNode,
-                                   QueryMetadataInterface metadata,
-                                   CapabilitiesFinder capFinder,
-                                   PlanNode parentNode, AnalysisRecord record) throws QueryMetadataException,
-                                                       TeiidComponentException {
-        // Find the model for this node by getting ACCESS node's model
-        Object modelID = getModelIDFromAccess(accessNode, metadata);
-        if(modelID == null) {
-            // Couldn't determine model ID, so give up
-            return false;
-        } 
-        
-        List<OrderByItem> sortCols = ((OrderBy)parentNode.getProperty(NodeConstants.Info.SORT_ORDER)).getOrderByItems();
-        for (OrderByItem symbol : sortCols) {
-            //TODO: this check shouldn't be necessary, since the order by is not introducing new expressions
-            if(! canPushSymbol(symbol.getSymbol(), true, modelID, metadata, capFinder, record)) {
-                return false;
-            }
-            boolean supportsNullOrdering = CapabilitiesUtil.supports(Capability.QUERY_ORDERBY_NULL_ORDERING, modelID, metadata, capFinder);
-            NullOrder defaultNullOrder = CapabilitiesUtil.getDefaultNullOrder(modelID, metadata, capFinder);
-            if (symbol.getNullOrdering() != null) {
-        		if (!supportsNullOrdering) {
-        			if (symbol.getNullOrdering() == NullOrdering.FIRST) {
-        				if (defaultNullOrder != NullOrder.FIRST && !(symbol.isAscending() && defaultNullOrder == NullOrder.LOW) 
-        						&& !(!symbol.isAscending() && defaultNullOrder == NullOrder.HIGH)) {
-        					return false;
-        				}
-        			} else if (defaultNullOrder != NullOrder.LAST && !(symbol.isAscending() && defaultNullOrder == NullOrder.HIGH) 
-        					&& !(!symbol.isAscending() && defaultNullOrder == NullOrder.LOW)) {
-    					return false;
-    				} 
-    				symbol.setNullOrdering(null);
-        		} 
-            } else if (supportsNullOrdering && defaultNullOrder != NullOrder.LOW) {
-            	//try to match the expected default of low
-        		if (symbol.isAscending()) {
-        			if (defaultNullOrder != NullOrder.FIRST) {
-        				symbol.setNullOrdering(NullOrdering.FIRST);
-        			}
-        		} else if (defaultNullOrder != NullOrder.LAST) {
-        			symbol.setNullOrdering(NullOrdering.LAST);
-        		}
-            }
-        }
-        
-        if (accessNode.getLastChild() != null) {
-            //check to see if the sort applies to a union
-            if (accessNode.getLastChild().getType() == NodeConstants.Types.SET_OP) {
-                return CapabilitiesUtil.supportsSetQueryOrderBy(modelID, metadata, capFinder);
-            }
-            //check to see the plan is not in a consistent state to have a sort applied
-            if (accessNode.getLastChild().getType() == NodeConstants.Types.TUPLE_LIMIT) {
-                return false;
-            }
-        }
-        
-        if (!CapabilitiesUtil.checkElementsAreSearchable(sortCols, metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
-        	return false;
-        }
-        
-        // If model supports the support constant parameter, then move access node
-        if (!CapabilitiesUtil.supportsOrderBy(modelID, metadata, capFinder)) {
-        	return false;
-        }
-        
-        /* If we have an unrelated sort it cannot be pushed down if it's not supported by the source
-         * 
-         * TODO: we should be able to work this
-         */
-        if (parentNode.hasBooleanProperty(NodeConstants.Info.UNRELATED_SORT) && !CapabilitiesUtil.supports(Capability.QUERY_ORDERBY_UNRELATED, modelID, metadata, capFinder)) {
-        	return false;
-        }
-        
-        return true;
-    }
-
-    /** 
-     * @param accessNode
-     * @param metadata
-     * @param capFinder
-     * @param parentNode
-     * @return
-     * @throws QueryMetadataException
-     * @throws TeiidComponentException
-     * @throws QueryPlannerException
-     */
-    static boolean canRaiseOverSelect(PlanNode accessNode,
-                                        QueryMetadataInterface metadata,
-                                        CapabilitiesFinder capFinder,
-                                        PlanNode parentNode, AnalysisRecord record) throws QueryMetadataException,
-                                                            TeiidComponentException,
-                                                            QueryPlannerException {
-        if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_PHANTOM)) {
-            return true;
-        }
-                
-        // Find the model for this node by getting ACCESS node's model
-        Object modelID = getModelIDFromAccess(accessNode, metadata);
-        if(modelID == null) {
-            // Couldn't determine model ID, so give up
-            return false;
-        } 
-        
-        if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_HAVING) && !CapabilitiesUtil.supports(Capability.QUERY_HAVING, modelID, metadata, capFinder)) {
-        	recordDebug("cannot push having, since having is not supported by source", parentNode, record); //$NON-NLS-1$
-        	return false;
-        }
-        
-        //don't push criteria into an invalid location above an ordered limit - shouldn't happen 
-        PlanNode limitNode = NodeEditor.findNodePreOrder(accessNode, NodeConstants.Types.TUPLE_LIMIT, NodeConstants.Types.SOURCE);
-        if (limitNode != null && FrameUtil.isOrderedLimit(limitNode)) {
-        	return false;
-        }
-        
-        Criteria crit = (Criteria) parentNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
-        
-        if(!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(crit, modelID, metadata, capFinder, record) ) { 
-            return false;                        
-        } 
-        
-        if (accessNode.getFirstChild() != null && accessNode.getFirstChild().getType() == NodeConstants.Types.SET_OP) {
-            return false; //inconsistent select position - RulePushSelectCriteria is too greedy
-        }
-                
-        return true;
-    }  
-            
-    /**
-     *  
-     * @param symbol Symbol to check
-     * @param inSelectClause True if evaluating in the context of a SELECT clause
-     * @param modelID Model
-     * @param metadata Metadata
-     * @param capFinder Capabilities finder
-     * @return True if can push symbol to source
-     * @throws TeiidComponentException
-     * @throws QueryMetadataException
-     * @since 4.1.2
-     */
-    private static boolean canPushSymbol(SingleElementSymbol symbol, boolean inSelectClause, Object modelID, 
-    		QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord record) 
-    throws TeiidComponentException, QueryMetadataException {
-
-        Expression expr = SymbolMap.getExpression(symbol);
-        
-        // Do the normal checks
-        if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(expr, modelID, metadata, capFinder, record)) {
-            return false;
-        }
-        
-        if(inSelectClause && !(expr instanceof ElementSymbol || expr instanceof AggregateSymbol) 
-        		&& !CapabilitiesUtil.supportsSelectExpression(modelID, metadata, capFinder)) {
-    		return false;
-        }                
-         
-        // By default, no reason we can't push
-        return true;
-    }
-    
-    static PlanNode performRaise(PlanNode rootNode, PlanNode accessNode, PlanNode parentNode) {
-        NodeEditor.removeChildNode(parentNode, accessNode);
-        parentNode.addAsParent(accessNode);
-        PlanNode grandparentNode = accessNode.getParent();
-        if(grandparentNode != null) {
-            return rootNode;
-        }
-        return accessNode;
-    }
-
-    /**
-     * Determine whether an access node can be raised over the specified join node.
-     * 
-     * This method can also be used to determine if a join node "A", parent of another join
-     * node "B", will have it's access raised.  This is needed to help determine if node
-     * "B" will have access raised over it.  In this scenario, the parameter will be true.
-     * When this method is called normally from the "execute" method, that param will be false.
-     *   
-     * @param joinNode Join node that might be pushed underneath the access node
-     * @param metadata Metadata information
-     * @param capFinder CapabilitiesFinder
-     * @return The modelID if the raise can proceed and what common model these combined
-     * nodes will be sent to
-     */
-	private static Object canRaiseOverJoin(Object modelId, PlanNode joinNode, QueryMetadataInterface metadata, 
-			CapabilitiesFinder capFinder, boolean afterJoinPlanning, AnalysisRecord record) 
-		throws QueryMetadataException, TeiidComponentException {
-		
-        List crits = (List) joinNode.getProperty(NodeConstants.Info.JOIN_CRITERIA);
-        JoinType type = (JoinType) joinNode.getProperty(NodeConstants.Info.JOIN_TYPE);
-        
-        //let ruleplanjoins handle this case
-        if (!afterJoinPlanning && type == JoinType.JOIN_CROSS && joinNode.getParent().getType() == NodeConstants.Types.JOIN) {
-            JoinType jt = (JoinType)joinNode.getParent().getProperty(NodeConstants.Info.JOIN_TYPE);
-            if (!jt.isOuter()) {
-                return null;
-            }
-        }
-        
-        if (joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE) != null) {
-            return null;
-        }
-        
-        //if a join has access patterns that are unsatisfied, then the raise cannot occur
-        if (joinNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
-            return null;
-        }
-        
-        //if I'm on the inner side of an outer join, then and we have a criteria restriction, then I can't be pushed
-		if (type.isOuter() && CapabilitiesUtil.getSupportedJoinCriteria(modelId, metadata, capFinder) != SupportedJoinCriteria.ANY) {
-			PlanNode critNode = NodeEditor.findNodePreOrder(joinNode.getLastChild(), NodeConstants.Types.SELECT, NodeConstants.Types.SOURCE);
-			if (critNode != null) {
-				return null;
-			}
-			if (type == JoinType.JOIN_FULL_OUTER) {
-				critNode = NodeEditor.findNodePreOrder(joinNode.getFirstChild(), NodeConstants.Types.SELECT, NodeConstants.Types.SOURCE);
-				if (critNode != null) {
-					return null;
-				}	
-			}
-		}
-        
-        return canRaiseOverJoin(joinNode.getChildren(), metadata, capFinder, crits, type, record);		
-	}
-
-    static Object canRaiseOverJoin(List<PlanNode> children,
-                                           QueryMetadataInterface metadata,
-                                           CapabilitiesFinder capFinder,
-                                           List<Criteria> crits,
-                                           JoinType type, AnalysisRecord record) throws QueryMetadataException,
-                                                         TeiidComponentException {
-        //we only want to consider binary joins
-        if (children.size() != 2) {
-        	return null;
-        }
-
-    	Object modelID = null;
-        Set<Object> groupIDs = new HashSet<Object>();
-        int groupCount = 0;
-        
-		for (PlanNode childNode : children) {
-			if(childNode.getType() != NodeConstants.Types.ACCESS 
-					|| childNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
-                return null;
-            }
-			Object accessModelID = getModelIDFromAccess(childNode, metadata);
-            if(accessModelID == null) { 
-                return null;
-            }
-            
-            groupCount += childNode.getGroups().size();
-
-			// Add all group metadata IDs to the list but check before each to make 
-			// sure group hasn't already been seen - if so, bail out - this is a self join
-            // Unless model supports self joins, in which case, don't bail out.
-
-            boolean supportsSelfJoins = CapabilitiesUtil.supportsSelfJoins(accessModelID, metadata, capFinder);
-            
-            if (!supportsSelfJoins) {
-                for (GroupSymbol groupSymbol : childNode.getGroups()) {
-    			    Object groupID = groupSymbol.getMetadataID();
-    			    if(!groupIDs.add(groupID)) {
-    			        // Already seen group - can't raise access over self join
-    			        return null;
-    			    }
-    			}
-            }
-            			
-            //check the join criteria now that we know the model
-			if(modelID == null) {
-                
-        		if (!CapabilitiesUtil.supportsJoin(accessModelID, type, metadata, capFinder)) {
-				   return null;
-        		}
-        		SupportedJoinCriteria sjc = CapabilitiesUtil.getSupportedJoinCriteria(accessModelID, metadata, capFinder);
-				
-        		/*
-        		 * Key joins must be left linear
-        		 */
-        		if (sjc == SupportedJoinCriteria.KEY && children.get(1).getGroups().size() != 1) {
-        			return null;
-        		}
-        		
-				if(crits != null && !crits.isEmpty()) {
-					List<Object> leftIds = null;
-					List<Object> rightIds = null;
-					GroupSymbol leftGroup = null;
-					for (Criteria crit : crits) {
-				        if (!isSupportedJoinCriteria(sjc, crit, accessModelID, metadata, capFinder, record)) {
-				        	return null;
-				        }
-			        	if (sjc != SupportedJoinCriteria.KEY) {
-			        		continue;
-			        	}
-			        	//key join
-			        	//TODO: this would be much simpler if we could rely on rulechoosejoinstrategy running first
-			        	if (leftIds == null) {
-			        		leftIds = new ArrayList<Object>();
-			        		rightIds = new ArrayList<Object>();
-			        	}
-			        	ElementSymbol leftSymbol = (ElementSymbol)((CompareCriteria)crit).getLeftExpression();
-			        	ElementSymbol rightSymbol = (ElementSymbol)((CompareCriteria)crit).getRightExpression();
-			        	if ((children.get(0).getGroups().contains(leftSymbol.getGroupSymbol()) && children.get(1).getGroups().contains(rightSymbol.getGroupSymbol()))
-			        			|| (children.get(1).getGroups().contains(leftSymbol.getGroupSymbol()) && children.get(0).getGroups().contains(rightSymbol.getGroupSymbol()))) {
-			        		boolean left = children.get(0).getGroups().contains(leftSymbol.getGroupSymbol());
-			        		if (leftGroup == null) {
-			        			leftGroup = left?leftSymbol.getGroupSymbol():rightSymbol.getGroupSymbol();
-			        		} else if (!leftGroup.equals(left?leftSymbol.getGroupSymbol():rightSymbol.getGroupSymbol())) {
-			        			return null;
-			        		}
-			        		if (left) {
-				        		leftIds.add(leftSymbol.getMetadataID());
-				        		rightIds.add(rightSymbol.getMetadataID());
-			        		} else {
-			        			rightIds.add(leftSymbol.getMetadataID());
-				        		leftIds.add(rightSymbol.getMetadataID());
-			        		}
-			        	} else {
-			        		return null;
-			        	}
-					}
-					if (leftIds != null &&
-							!matchesForeignKey(metadata, leftIds, rightIds,	leftGroup) 
-							&& !matchesForeignKey(metadata, rightIds, leftIds, children.get(1).getGroups().iterator().next())) {
-						return null;
-					}
-                } else if (sjc != SupportedJoinCriteria.ANY) {
-                	return null; //cross join not supported
-                }
-				
-				modelID = accessModelID;
-				
-			} else if(!CapabilitiesUtil.isSameConnector(modelID, accessModelID, metadata, capFinder)) { 
-				return null;							
-			}
-		} // end walking through join node's children
-
-		int maxGroups = CapabilitiesUtil.getMaxFromGroups(modelID, metadata, capFinder);
-		
-		if (maxGroups != -1 && maxGroups < groupCount) {
-		    return null;
-		}
-		
-		return modelID;
-    }
-    
-    /**
-     * Checks criteria one predicate at a time.  Only tests up to the equi restriction.
-     */
-    static boolean isSupportedJoinCriteria(SupportedJoinCriteria sjc, Criteria crit, Object accessModelID, 
-    		QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord record) 
-    throws QueryMetadataException, TeiidComponentException {
-    	if(!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(crit, accessModelID, metadata, capFinder, record) ) { 
-            return false;                        
-        } 
-        if (sjc == SupportedJoinCriteria.ANY) {
-        	return true;
-        }
-        //theta join must be between elements with a compare predicate
-    	if (!(crit instanceof CompareCriteria)) {
-    		return false;
-    	}
-    	CompareCriteria cc = (CompareCriteria)crit;
-    	if (!(cc.getLeftExpression() instanceof ElementSymbol)) {
-    		return false;
-    	}
-    	if (!(cc.getRightExpression() instanceof ElementSymbol)) {
-    		return false;
-    	}
-    	if (sjc == SupportedJoinCriteria.THETA) {
-    		return true;
-    	}
-    	//equi must use the equality operator
-    	if (cc.getOperator() != CompareCriteria.EQ) {
-    		return false;
-    	}
-		return true;
-    }
-
-    /**
-     * TODO: gracefully handle too much criteria
-     */
-	private static boolean matchesForeignKey(QueryMetadataInterface metadata,
-			List<Object> leftIds, List<Object> rightIds, GroupSymbol leftGroup)
-			throws TeiidComponentException, QueryMetadataException {
-		Collection fks = metadata.getForeignKeysInGroup(leftGroup.getMetadataID());
-		for (Object fk : fks) {
-			List fkColumns = metadata.getElementIDsInKey(fk);
-			if (!leftIds.containsAll(fkColumns) || leftIds.size() != fkColumns.size()) {
-				continue;
-			}
-			Object pk = metadata.getPrimaryKeyIDForForeignKeyID(fk);
-			List pkColumns = metadata.getElementIDsInKey(pk);
-			if (rightIds.containsAll(pkColumns) && rightIds.size() == pkColumns.size()) {
-				return true;
-			}
-		}
-		return false;
-	}
-    
-    static PlanNode raiseAccessOverJoin(PlanNode joinNode, Object modelID, boolean insert) {
-		PlanNode leftAccess = joinNode.getFirstChild();
-		PlanNode rightAccess = joinNode.getLastChild();
-
-		// Remove old access nodes - this will automatically add children of access nodes to join node
-		NodeEditor.removeChildNode(joinNode, leftAccess);
-		NodeEditor.removeChildNode(joinNode, rightAccess);
-        
-        //Set for later possible use, even though this isn't an access node
-        joinNode.setProperty(NodeConstants.Info.MODEL_ID, modelID);
-
-		// Insert new access node above join node 
-		PlanNode newAccess = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
-		newAccess.setProperty(NodeConstants.Info.MODEL_ID, modelID);
-		newAccess.addGroups(rightAccess.getGroups());
-		newAccess.addGroups(leftAccess.getGroups());
-        
-        // Combine hints if necessary
-        Object leftHint = leftAccess.getProperty(NodeConstants.Info.MAKE_DEP);
-        if(leftHint != null) {
-            newAccess.setProperty(NodeConstants.Info.MAKE_DEP, leftHint);
-        } else {
-            Object rightHint = rightAccess.getProperty(NodeConstants.Info.MAKE_DEP);
-            if(rightHint != null) {
-                newAccess.setProperty(NodeConstants.Info.MAKE_DEP, rightHint);
-            }    
-        }
-        RulePlaceAccess.copyDependentHints(leftAccess, newAccess);
-        RulePlaceAccess.copyDependentHints(rightAccess, newAccess);
-        RulePlaceAccess.copyDependentHints(joinNode, newAccess);
-        
-        if (insert) {
-            joinNode.addAsParent(newAccess);
-        } else {
-            newAccess.addFirstChild(joinNode);
-        }
-        
-        return newAccess;
-	}
-
-    /**
-     * Get modelID for Access node and cache the result in the Access node.
-     * @param accessNode Access node
-     * @param metadata Metadata access
-     * @return Object Model ID or null if not found.
-     * @throws QueryMetadataException
-     * @throws TeiidComponentException
-     */
-    static Object getModelIDFromAccess(PlanNode accessNode, QueryMetadataInterface metadata) 
-    throws QueryMetadataException, TeiidComponentException {
-
-        Object accessModelID = accessNode.getProperty(NodeConstants.Info.MODEL_ID);
-        if(accessModelID == null) {
-            GroupSymbol group = accessNode.getGroups().iterator().next();
-            if(metadata.isVirtualGroup(group.getMetadataID())) {
-                return null;
-            }
-            accessModelID = metadata.getModelID(group.getMetadataID());
-    
-            accessNode.setProperty(NodeConstants.Info.MODEL_ID, accessModelID);
-        } 
-        
-        return accessModelID;    
-    }
-    
-    private static boolean canRaiseOverSetQuery(PlanNode setOpNode,
-                                     QueryMetadataInterface metadata,
-                                     CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException {
-        
-        Object modelID = null;
-        
-        for (PlanNode childNode : setOpNode.getChildren()) {
-            if(childNode.getType() != NodeConstants.Types.ACCESS) {
-                return false;
-            } 
-            
-            if (FrameUtil.getNonQueryCommand(childNode) != null || FrameUtil.getNestedPlan(childNode) != null) {
-                return false;
-            }
-            
-            // Get model and check that it exists
-            Object accessModelID = getModelIDFromAccess(childNode, metadata);
-            if(accessModelID == null) {
-                return false;
-            }
-            
-            // Reconcile this access node's model ID with existing                                             
-            if(modelID == null) {
-                modelID = accessModelID;
-                
-                if(! CapabilitiesUtil.supportsSetOp(accessModelID, (Operation)setOpNode.getProperty(NodeConstants.Info.SET_OPERATION), metadata, capFinder)) {
-                    return false;
-                }
-            } else if(!CapabilitiesUtil.isSameConnector(modelID, accessModelID, metadata, capFinder)) {
-                return false;
-            }      
-            if (!setOpNode.hasBooleanProperty(NodeConstants.Info.USE_ALL) 
-            		&&  !CapabilitiesUtil.checkElementsAreSearchable((List)NodeEditor.findNodePreOrder(childNode, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS), metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
-            	return false;
-            }
-
-        }
-        return true;
-    }
-    
-	public String toString() {
-		return "RaiseAccess"; //$NON-NLS-1$
-	}
-	
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,841 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.optimizer.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.language.SortSpecification.NullOrdering;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.SupportConstants;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.optimizer.relational.OptimizerRule;
+import org.teiid.query.optimizer.relational.RuleStack;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants;
+import org.teiid.query.optimizer.relational.plantree.NodeEditor;
+import org.teiid.query.optimizer.relational.plantree.NodeFactory;
+import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.OrderByItem;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.util.CommandContext;
+import org.teiid.translator.ExecutionFactory.NullOrder;
+import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
+
+
+public final class RuleRaiseAccess implements OptimizerRule {
+
+	public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
+		throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+        boolean afterJoinPlanning = !rules.contains(RuleConstants.PLAN_JOINS);
+        
+        // Loop until nothing has been raised - plan is then stable and can be returned
+        boolean raisedNode = true;
+        while(raisedNode) {
+            raisedNode = false;
+
+            for (PlanNode accessNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.ACCESS)) {
+                PlanNode newRoot = raiseAccessNode(plan, accessNode, metadata, capFinder, afterJoinPlanning, analysisRecord);
+                if(newRoot != null) {
+                    raisedNode = true;
+                    plan = newRoot;
+                }
+            }            
+        }
+        
+        return plan;
+	}
+    
+    /**
+     * @return null if nothing changed, and a new plan root if something changed
+     */
+    static PlanNode raiseAccessNode(PlanNode rootNode, PlanNode accessNode, QueryMetadataInterface metadata, 
+    		CapabilitiesFinder capFinder, boolean afterJoinPlanning, AnalysisRecord record) 
+    throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+        
+        PlanNode parentNode = accessNode.getParent();
+        if(parentNode == null) {
+            // Nothing to raise over
+            return null;
+        }
+        Object modelID = getModelIDFromAccess(accessNode, metadata);
+        if(modelID == null) {
+            return null;
+        }
+        
+        switch(parentNode.getType()) {
+            case NodeConstants.Types.JOIN:
+            {
+                modelID = canRaiseOverJoin(modelID, parentNode, metadata, capFinder, afterJoinPlanning, record);
+                if(modelID != null) {
+                    raiseAccessOverJoin(parentNode, modelID, true);                    
+                    return rootNode;
+                }
+                return null;
+            }            
+            case NodeConstants.Types.PROJECT:
+            {         
+                // Check that the PROJECT contains only functions that can be pushed                               
+                List projectCols = (List) parentNode.getProperty(NodeConstants.Info.PROJECT_COLS);
+                
+                for (int i = 0; i < projectCols.size(); i++) {
+                    SingleElementSymbol symbol = (SingleElementSymbol)projectCols.get(i);
+                    if(! canPushSymbol(symbol, true, modelID, metadata, capFinder, record)) {
+                        return null;
+                    } 
+                }
+                
+                /*
+                 * TODO: this creates an extraneous project node in many circumstances.
+                 * However we don't actually support project in this case, so allowing it to be pushed
+                 * causes problems with stored procedures and the assumptions made for proc/relational
+                 * planning. 
+                 */
+                if (FrameUtil.isProcedure(parentNode)) {
+                	return null;
+                }
+                                
+                return performRaise(rootNode, accessNode, parentNode);                
+            }
+            case NodeConstants.Types.DUP_REMOVE:
+            {     
+                // If model supports the support constant parameter, then move access node
+                if(!CapabilitiesUtil.supportsSelectDistinct(modelID, metadata, capFinder)) {
+                	recordDebug("cannot push dupremove, since distinct is not supported by source", parentNode, record); //$NON-NLS-1$
+                	return null;
+                }
+                
+                //TODO: this check is too specific the columns could be used in expressions that are comparable
+                if (!CapabilitiesUtil.checkElementsAreSearchable((List)NodeEditor.findNodePreOrder(parentNode, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS), metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
+                	recordDebug("cannot push dupremove, since not all columns are comparable at the source", parentNode, record); //$NON-NLS-1$
+                	return null;
+                }
+                
+                return performRaise(rootNode, accessNode, parentNode);
+            }
+            case NodeConstants.Types.SORT:
+            {         
+                if (canRaiseOverSort(accessNode, metadata, capFinder, parentNode, record)) {
+                    return performRaise(rootNode, accessNode, parentNode);
+                }
+                return null;
+            }            
+            case NodeConstants.Types.GROUP:            
+            {                
+                Set<AggregateSymbol> aggregates = RulePushAggregates.collectAggregates(parentNode);
+                if (canRaiseOverGroupBy(parentNode, accessNode, aggregates, metadata, capFinder, record)) {
+                    return performRaise(rootNode, accessNode, parentNode);
+                }
+                return null;
+            } 
+            case NodeConstants.Types.SET_OP:
+            	if (!canRaiseOverSetQuery(parentNode, metadata, capFinder)) {
+            		return null;
+            	}
+
+            	for (PlanNode node : new ArrayList<PlanNode>(parentNode.getChildren())) {
+            		if (node == accessNode) {
+            			continue;
+            		}
+        			NodeEditor.removeChildNode(parentNode, node);
+            	}
+            	accessNode.getGroups().clear();
+                return performRaise(rootNode, accessNode, parentNode);
+            case NodeConstants.Types.SELECT:            
+            {
+            	if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET)) {
+            		return null;
+            	}
+            	if (canRaiseOverSelect(accessNode, metadata, capFinder, parentNode, record)) {
+                    RulePushSelectCriteria.satisfyAccessPatterns(parentNode, accessNode);
+                    return performRaise(rootNode, accessNode, parentNode);                      
+            	}
+            	//determine if we should push the select back up
+            	if (parentNode.getParent() == null) {
+            		return null;
+            	}
+        		PlanNode selectRoot = parentNode;
+        		while (selectRoot.getParent() != null && selectRoot.getParent().getType() == NodeConstants.Types.SELECT) {
+        			selectRoot = selectRoot.getParent();
+        		}
+        		if (selectRoot.getParent() == null || (selectRoot.getParent().getType() & (NodeConstants.Types.PROJECT|NodeConstants.Types.GROUP)) == selectRoot.getParent().getType()) {
+        			return null;
+        		}
+    			PlanNode grandParent = selectRoot.getParent();
+    			boolean isLeft = false;
+				isLeft = grandParent.getFirstChild() == selectRoot;
+				if (grandParent.getType() == NodeConstants.Types.JOIN) {
+					JoinType jt = (JoinType)grandParent.getProperty(NodeConstants.Info.JOIN_TYPE);
+					if (jt == JoinType.JOIN_FULL_OUTER || (jt == JoinType.JOIN_LEFT_OUTER && !isLeft)) {
+						return null;
+					}
+				}
+				grandParent.removeChild(selectRoot);
+				if (isLeft) {
+					grandParent.addFirstChild(accessNode);
+				} else {
+					grandParent.addLastChild(accessNode);
+				}
+    			PlanNode newParent = grandParent.getParent();
+				//TODO: use costing or heuristics instead of always raising
+    			PlanNode newRoot = raiseAccessNode(rootNode, accessNode, metadata, capFinder, afterJoinPlanning, record);
+    			if (newRoot == null) {
+					//return the tree to its original state
+    				parentNode.addFirstChild(accessNode);
+    				if (isLeft) {
+    					grandParent.addFirstChild(selectRoot);
+    				} else {
+    					grandParent.addLastChild(selectRoot);
+    				}
+    			} else {
+    				//attach the select nodes above the access node
+    				accessNode = grandParent.getParent();
+					if (newParent != null) {
+    					isLeft = newParent.getFirstChild() == accessNode;
+    					if (isLeft) {
+    						newParent.addFirstChild(selectRoot);
+    					} else {
+    						newParent.addLastChild(selectRoot);
+    					}
+    				} else {
+    					newRoot = selectRoot;
+    				}
+					parentNode.addFirstChild(accessNode);
+    				return newRoot;
+    			}
+                return null;
+            }   
+            case NodeConstants.Types.SOURCE:
+            {
+                //if a source has access patterns that are unsatisfied, then the raise cannot occur
+                if (parentNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
+                    return null;
+                }
+                
+                SymbolMap references = (SymbolMap)parentNode.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
+                if (references != null) {
+                	return null;
+                }
+                
+                //raise only if there is no intervening project into
+                PlanNode parentProject = NodeEditor.findParent(parentNode, NodeConstants.Types.PROJECT);
+                GroupSymbol intoGroup = (GroupSymbol)parentProject.getProperty(NodeConstants.Info.INTO_GROUP); 
+                if (intoGroup != null && parentProject.getParent() == null) {
+                	if (CapabilitiesUtil.supports(Capability.INSERT_WITH_QUERYEXPRESSION, modelID, metadata, capFinder) && CapabilitiesUtil.isSameConnector(modelID, metadata.getModelID(intoGroup.getMetadataID()), metadata, capFinder)) {
+                    	rootNode = performRaise(rootNode, accessNode, parentNode);
+                    	return performRaise(rootNode, accessNode, parentProject);
+                	}
+                	return null;
+                } else if (!CapabilitiesUtil.supportsInlineView(modelID, metadata, capFinder)) {
+                	return null;
+                }
+
+                //is there another query that will be used with this source
+                if (FrameUtil.getNonQueryCommand(accessNode) != null || FrameUtil.getNestedPlan(accessNode) != null) {
+                	return null;
+                }
+                                
+                //switch to inline view and change the group on the access to that of the source
+            	parentNode.setProperty(NodeConstants.Info.INLINE_VIEW, Boolean.TRUE);
+            	accessNode.getGroups().clear();
+            	accessNode.addGroups(parentNode.getGroups());
+                RulePlaceAccess.copyDependentHints(parentNode, accessNode);
+            	return performRaise(rootNode, accessNode, parentNode);
+            }
+            case NodeConstants.Types.TUPLE_LIMIT:
+            {
+                return RulePushLimit.raiseAccessOverLimit(rootNode, accessNode, metadata, capFinder, parentNode);
+            }
+            default: 
+            {
+                return null;
+            }                      
+        }        
+    }
+
+    static boolean canRaiseOverGroupBy(PlanNode groupNode,
+                                         PlanNode accessNode,
+                                         Collection<? extends SingleElementSymbol> aggregates,
+                                         QueryMetadataInterface metadata,
+                                         CapabilitiesFinder capFinder, AnalysisRecord record) throws QueryMetadataException,
+                                                        TeiidComponentException {
+        Object modelID = getModelIDFromAccess(accessNode, metadata);
+        if(modelID == null) {
+            return false;
+        }
+        List<SingleElementSymbol> groupCols = (List<SingleElementSymbol>)groupNode.getProperty(NodeConstants.Info.GROUP_COLS);
+        if(!CapabilitiesUtil.supportsAggregates(groupCols, modelID, metadata, capFinder)) {
+        	recordDebug("cannot push group by, since group by is not supported by source", groupNode, record); //$NON-NLS-1$
+            return false;
+        }
+        if (groupCols != null) {
+            for (SingleElementSymbol singleElementSymbol : groupCols) {
+                if (!canPushSymbol(singleElementSymbol, false, modelID, metadata, capFinder, record)) {
+                    return false;
+                }
+            }
+        }
+        if (aggregates != null) {
+            for (SingleElementSymbol aggregateSymbol : aggregates) {
+                if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(aggregateSymbol, modelID, metadata, capFinder, record)) {
+                    return false;
+                }
+            }
+        }
+        return CapabilitiesUtil.checkElementsAreSearchable(groupCols, metadata, SupportConstants.Element.SEARCHABLE_COMPARE);
+    }
+
+	private static void recordDebug(String message, PlanNode node, AnalysisRecord record) {
+		if (record != null && record.recordDebug()) {
+			record.println(message + " " + node.nodeToString()); //$NON-NLS-1$
+		}
+	}
+    
+    static boolean canRaiseOverSort(PlanNode accessNode,
+                                   QueryMetadataInterface metadata,
+                                   CapabilitiesFinder capFinder,
+                                   PlanNode parentNode, AnalysisRecord record) throws QueryMetadataException,
+                                                       TeiidComponentException {
+        // Find the model for this node by getting ACCESS node's model
+        Object modelID = getModelIDFromAccess(accessNode, metadata);
+        if(modelID == null) {
+            // Couldn't determine model ID, so give up
+            return false;
+        } 
+        
+        List<OrderByItem> sortCols = ((OrderBy)parentNode.getProperty(NodeConstants.Info.SORT_ORDER)).getOrderByItems();
+        for (OrderByItem symbol : sortCols) {
+            //TODO: this check shouldn't be necessary, since the order by is not introducing new expressions
+            if(! canPushSymbol(symbol.getSymbol(), true, modelID, metadata, capFinder, record)) {
+                return false;
+            }
+            boolean supportsNullOrdering = CapabilitiesUtil.supports(Capability.QUERY_ORDERBY_NULL_ORDERING, modelID, metadata, capFinder);
+            NullOrder defaultNullOrder = CapabilitiesUtil.getDefaultNullOrder(modelID, metadata, capFinder);
+            if (symbol.getNullOrdering() != null) {
+        		if (!supportsNullOrdering) {
+        			if (symbol.getNullOrdering() == NullOrdering.FIRST) {
+        				if (defaultNullOrder != NullOrder.FIRST && !(symbol.isAscending() && defaultNullOrder == NullOrder.LOW) 
+        						&& !(!symbol.isAscending() && defaultNullOrder == NullOrder.HIGH)) {
+        					return false;
+        				}
+        			} else if (defaultNullOrder != NullOrder.LAST && !(symbol.isAscending() && defaultNullOrder == NullOrder.HIGH) 
+        					&& !(!symbol.isAscending() && defaultNullOrder == NullOrder.LOW)) {
+    					return false;
+    				} 
+    				symbol.setNullOrdering(null);
+        		} 
+            } else if (supportsNullOrdering && defaultNullOrder != NullOrder.LOW) {
+            	//try to match the expected default of low
+        		if (symbol.isAscending()) {
+        			if (defaultNullOrder != NullOrder.FIRST) {
+        				symbol.setNullOrdering(NullOrdering.FIRST);
+        			}
+        		} else if (defaultNullOrder != NullOrder.LAST) {
+        			symbol.setNullOrdering(NullOrdering.LAST);
+        		}
+            }
+        }
+        
+        if (accessNode.getLastChild() != null) {
+            //check to see if the sort applies to a union
+            if (accessNode.getLastChild().getType() == NodeConstants.Types.SET_OP) {
+                return CapabilitiesUtil.supportsSetQueryOrderBy(modelID, metadata, capFinder);
+            }
+            //check to see the plan is not in a consistent state to have a sort applied
+            if (accessNode.getLastChild().getType() == NodeConstants.Types.TUPLE_LIMIT) {
+                return false;
+            }
+        }
+        
+        if (!CapabilitiesUtil.checkElementsAreSearchable(sortCols, metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
+        	return false;
+        }
+        
+        // If model supports the support constant parameter, then move access node
+        if (!CapabilitiesUtil.supportsOrderBy(modelID, metadata, capFinder)) {
+        	return false;
+        }
+        
+        /* If we have an unrelated sort it cannot be pushed down if it's not supported by the source
+         * 
+         * TODO: we should be able to work this
+         */
+        if (parentNode.hasBooleanProperty(NodeConstants.Info.UNRELATED_SORT) && !CapabilitiesUtil.supports(Capability.QUERY_ORDERBY_UNRELATED, modelID, metadata, capFinder)) {
+        	return false;
+        }
+        
+        return true;
+    }
+
+    /** 
+     * @param accessNode
+     * @param metadata
+     * @param capFinder
+     * @param parentNode
+     * @return
+     * @throws QueryMetadataException
+     * @throws TeiidComponentException
+     * @throws QueryPlannerException
+     */
+    static boolean canRaiseOverSelect(PlanNode accessNode,
+                                        QueryMetadataInterface metadata,
+                                        CapabilitiesFinder capFinder,
+                                        PlanNode parentNode, AnalysisRecord record) throws QueryMetadataException,
+                                                            TeiidComponentException,
+                                                            QueryPlannerException {
+        if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_PHANTOM)) {
+            return true;
+        }
+                
+        // Find the model for this node by getting ACCESS node's model
+        Object modelID = getModelIDFromAccess(accessNode, metadata);
+        if(modelID == null) {
+            // Couldn't determine model ID, so give up
+            return false;
+        } 
+        
+        if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_HAVING) && !CapabilitiesUtil.supports(Capability.QUERY_HAVING, modelID, metadata, capFinder)) {
+        	recordDebug("cannot push having, since having is not supported by source", parentNode, record); //$NON-NLS-1$
+        	return false;
+        }
+        
+        //don't push criteria into an invalid location above an ordered limit - shouldn't happen 
+        PlanNode limitNode = NodeEditor.findNodePreOrder(accessNode, NodeConstants.Types.TUPLE_LIMIT, NodeConstants.Types.SOURCE);
+        if (limitNode != null && FrameUtil.isOrderedLimit(limitNode)) {
+        	return false;
+        }
+        
+        Criteria crit = (Criteria) parentNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+        
+        if(!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(crit, modelID, metadata, capFinder, record) ) { 
+            return false;                        
+        } 
+        
+        if (accessNode.getFirstChild() != null && accessNode.getFirstChild().getType() == NodeConstants.Types.SET_OP) {
+            return false; //inconsistent select position - RulePushSelectCriteria is too greedy
+        }
+                
+        return true;
+    }  
+            
+    /**
+     *  
+     * @param symbol Symbol to check
+     * @param inSelectClause True if evaluating in the context of a SELECT clause
+     * @param modelID Model
+     * @param metadata Metadata
+     * @param capFinder Capabilities finder
+     * @return True if can push symbol to source
+     * @throws TeiidComponentException
+     * @throws QueryMetadataException
+     * @since 4.1.2
+     */
+    private static boolean canPushSymbol(SingleElementSymbol symbol, boolean inSelectClause, Object modelID, 
+    		QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord record) 
+    throws TeiidComponentException, QueryMetadataException {
+
+        Expression expr = SymbolMap.getExpression(symbol);
+        
+        // Do the normal checks
+        if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(expr, modelID, metadata, capFinder, record)) {
+            return false;
+        }
+        
+        if(inSelectClause && !(expr instanceof ElementSymbol || expr instanceof AggregateSymbol) 
+        		&& !CapabilitiesUtil.supportsSelectExpression(modelID, metadata, capFinder)) {
+    		return false;
+        }                
+         
+        // By default, no reason we can't push
+        return true;
+    }
+    
+    static PlanNode performRaise(PlanNode rootNode, PlanNode accessNode, PlanNode parentNode) {
+    	accessNode.removeProperty(NodeConstants.Info.EST_CARDINALITY);
+        NodeEditor.removeChildNode(parentNode, accessNode);
+        parentNode.addAsParent(accessNode);
+        PlanNode grandparentNode = accessNode.getParent();
+        if(grandparentNode != null) {
+            return rootNode;
+        }
+        return accessNode;
+    }
+
+    /**
+     * Determine whether an access node can be raised over the specified join node.
+     * 
+     * This method can also be used to determine if a join node "A", parent of another join
+     * node "B", will have it's access raised.  This is needed to help determine if node
+     * "B" will have access raised over it.  In this scenario, the parameter will be true.
+     * When this method is called normally from the "execute" method, that param will be false.
+     *   
+     * @param joinNode Join node that might be pushed underneath the access node
+     * @param metadata Metadata information
+     * @param capFinder CapabilitiesFinder
+     * @return The modelID if the raise can proceed and what common model these combined
+     * nodes will be sent to
+     */
+	private static Object canRaiseOverJoin(Object modelId, PlanNode joinNode, QueryMetadataInterface metadata, 
+			CapabilitiesFinder capFinder, boolean afterJoinPlanning, AnalysisRecord record) 
+		throws QueryMetadataException, TeiidComponentException {
+		
+        List crits = (List) joinNode.getProperty(NodeConstants.Info.JOIN_CRITERIA);
+        JoinType type = (JoinType) joinNode.getProperty(NodeConstants.Info.JOIN_TYPE);
+        
+        //let ruleplanjoins handle this case
+        if (!afterJoinPlanning && type == JoinType.JOIN_CROSS && joinNode.getParent().getType() == NodeConstants.Types.JOIN) {
+            JoinType jt = (JoinType)joinNode.getParent().getProperty(NodeConstants.Info.JOIN_TYPE);
+            if (!jt.isOuter()) {
+                return null;
+            }
+        }
+        
+        if (joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE) != null) {
+            return null;
+        }
+        
+        //if a join has access patterns that are unsatisfied, then the raise cannot occur
+        if (joinNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
+            return null;
+        }
+        
+        //if I'm on the inner side of an outer join, then and we have a criteria restriction, then I can't be pushed
+		if (type.isOuter() && CapabilitiesUtil.getSupportedJoinCriteria(modelId, metadata, capFinder) != SupportedJoinCriteria.ANY) {
+			PlanNode critNode = NodeEditor.findNodePreOrder(joinNode.getLastChild(), NodeConstants.Types.SELECT, NodeConstants.Types.SOURCE);
+			if (critNode != null) {
+				return null;
+			}
+			if (type == JoinType.JOIN_FULL_OUTER) {
+				critNode = NodeEditor.findNodePreOrder(joinNode.getFirstChild(), NodeConstants.Types.SELECT, NodeConstants.Types.SOURCE);
+				if (critNode != null) {
+					return null;
+				}	
+			}
+		}
+        
+        return canRaiseOverJoin(joinNode.getChildren(), metadata, capFinder, crits, type, record);		
+	}
+
+    static Object canRaiseOverJoin(List<PlanNode> children,
+                                           QueryMetadataInterface metadata,
+                                           CapabilitiesFinder capFinder,
+                                           List<Criteria> crits,
+                                           JoinType type, AnalysisRecord record) throws QueryMetadataException,
+                                                         TeiidComponentException {
+        //we only want to consider binary joins
+        if (children.size() != 2) {
+        	return null;
+        }
+
+    	Object modelID = null;
+        Set<Object> groupIDs = new HashSet<Object>();
+        int groupCount = 0;
+        
+		for (PlanNode childNode : children) {
+			if(childNode.getType() != NodeConstants.Types.ACCESS 
+					|| childNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
+                return null;
+            }
+			Object accessModelID = getModelIDFromAccess(childNode, metadata);
+            if(accessModelID == null) { 
+                return null;
+            }
+            
+            groupCount += childNode.getGroups().size();
+
+			// Add all group metadata IDs to the list but check before each to make 
+			// sure group hasn't already been seen - if so, bail out - this is a self join
+            // Unless model supports self joins, in which case, don't bail out.
+
+            boolean supportsSelfJoins = CapabilitiesUtil.supportsSelfJoins(accessModelID, metadata, capFinder);
+            
+            if (!supportsSelfJoins) {
+                for (GroupSymbol groupSymbol : childNode.getGroups()) {
+    			    Object groupID = groupSymbol.getMetadataID();
+    			    if(!groupIDs.add(groupID)) {
+    			        // Already seen group - can't raise access over self join
+    			        return null;
+    			    }
+    			}
+            }
+            			
+            //check the join criteria now that we know the model
+			if(modelID == null) {
+                
+        		if (!CapabilitiesUtil.supportsJoin(accessModelID, type, metadata, capFinder)) {
+				   return null;
+        		}
+        		SupportedJoinCriteria sjc = CapabilitiesUtil.getSupportedJoinCriteria(accessModelID, metadata, capFinder);
+				
+        		/*
+        		 * Key joins must be left linear
+        		 */
+        		if (sjc == SupportedJoinCriteria.KEY && children.get(1).getGroups().size() != 1) {
+        			return null;
+        		}
+        		
+				if(crits != null && !crits.isEmpty()) {
+					List<Object> leftIds = null;
+					List<Object> rightIds = null;
+					GroupSymbol leftGroup = null;
+					for (Criteria crit : crits) {
+				        if (!isSupportedJoinCriteria(sjc, crit, accessModelID, metadata, capFinder, record)) {
+				        	return null;
+				        }
+			        	if (sjc != SupportedJoinCriteria.KEY) {
+			        		continue;
+			        	}
+			        	//key join
+			        	//TODO: this would be much simpler if we could rely on rulechoosejoinstrategy running first
+			        	if (leftIds == null) {
+			        		leftIds = new ArrayList<Object>();
+			        		rightIds = new ArrayList<Object>();
+			        	}
+			        	ElementSymbol leftSymbol = (ElementSymbol)((CompareCriteria)crit).getLeftExpression();
+			        	ElementSymbol rightSymbol = (ElementSymbol)((CompareCriteria)crit).getRightExpression();
+			        	if ((children.get(0).getGroups().contains(leftSymbol.getGroupSymbol()) && children.get(1).getGroups().contains(rightSymbol.getGroupSymbol()))
+			        			|| (children.get(1).getGroups().contains(leftSymbol.getGroupSymbol()) && children.get(0).getGroups().contains(rightSymbol.getGroupSymbol()))) {
+			        		boolean left = children.get(0).getGroups().contains(leftSymbol.getGroupSymbol());
+			        		if (leftGroup == null) {
+			        			leftGroup = left?leftSymbol.getGroupSymbol():rightSymbol.getGroupSymbol();
+			        		} else if (!leftGroup.equals(left?leftSymbol.getGroupSymbol():rightSymbol.getGroupSymbol())) {
+			        			return null;
+			        		}
+			        		if (left) {
+				        		leftIds.add(leftSymbol.getMetadataID());
+				        		rightIds.add(rightSymbol.getMetadataID());
+			        		} else {
+			        			rightIds.add(leftSymbol.getMetadataID());
+				        		leftIds.add(rightSymbol.getMetadataID());
+			        		}
+			        	} else {
+			        		return null;
+			        	}
+					}
+					if (leftIds != null &&
+							!matchesForeignKey(metadata, leftIds, rightIds,	leftGroup) 
+							&& !matchesForeignKey(metadata, rightIds, leftIds, children.get(1).getGroups().iterator().next())) {
+						return null;
+					}
+                } else if (sjc != SupportedJoinCriteria.ANY) {
+                	return null; //cross join not supported
+                }
+				
+				modelID = accessModelID;
+				
+			} else if(!CapabilitiesUtil.isSameConnector(modelID, accessModelID, metadata, capFinder)) { 
+				return null;							
+			}
+		} // end walking through join node's children
+
+		int maxGroups = CapabilitiesUtil.getMaxFromGroups(modelID, metadata, capFinder);
+		
+		if (maxGroups != -1 && maxGroups < groupCount) {
+		    return null;
+		}
+		
+		return modelID;
+    }
+    
+    /**
+     * Checks criteria one predicate at a time.  Only tests up to the equi restriction.
+     */
+    static boolean isSupportedJoinCriteria(SupportedJoinCriteria sjc, Criteria crit, Object accessModelID, 
+    		QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord record) 
+    throws QueryMetadataException, TeiidComponentException {
+    	if(!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(crit, accessModelID, metadata, capFinder, record) ) { 
+            return false;                        
+        } 
+        if (sjc == SupportedJoinCriteria.ANY) {
+        	return true;
+        }
+        //theta join must be between elements with a compare predicate
+    	if (!(crit instanceof CompareCriteria)) {
+    		return false;
+    	}
+    	CompareCriteria cc = (CompareCriteria)crit;
+    	if (!(cc.getLeftExpression() instanceof ElementSymbol)) {
+    		return false;
+    	}
+    	if (!(cc.getRightExpression() instanceof ElementSymbol)) {
+    		return false;
+    	}
+    	if (sjc == SupportedJoinCriteria.THETA) {
+    		return true;
+    	}
+    	//equi must use the equality operator
+    	if (cc.getOperator() != CompareCriteria.EQ) {
+    		return false;
+    	}
+		return true;
+    }
+
+    /**
+     * TODO: gracefully handle too much criteria
+     */
+	private static boolean matchesForeignKey(QueryMetadataInterface metadata,
+			List<Object> leftIds, List<Object> rightIds, GroupSymbol leftGroup)
+			throws TeiidComponentException, QueryMetadataException {
+		Collection fks = metadata.getForeignKeysInGroup(leftGroup.getMetadataID());
+		for (Object fk : fks) {
+			List fkColumns = metadata.getElementIDsInKey(fk);
+			if (!leftIds.containsAll(fkColumns) || leftIds.size() != fkColumns.size()) {
+				continue;
+			}
+			Object pk = metadata.getPrimaryKeyIDForForeignKeyID(fk);
+			List pkColumns = metadata.getElementIDsInKey(pk);
+			if (rightIds.containsAll(pkColumns) && rightIds.size() == pkColumns.size()) {
+				return true;
+			}
+		}
+		return false;
+	}
+    
+    static PlanNode raiseAccessOverJoin(PlanNode joinNode, Object modelID, boolean insert) {
+		PlanNode leftAccess = joinNode.getFirstChild();
+		PlanNode rightAccess = joinNode.getLastChild();
+
+		// Remove old access nodes - this will automatically add children of access nodes to join node
+		NodeEditor.removeChildNode(joinNode, leftAccess);
+		NodeEditor.removeChildNode(joinNode, rightAccess);
+        
+        //Set for later possible use, even though this isn't an access node
+        joinNode.setProperty(NodeConstants.Info.MODEL_ID, modelID);
+
+		// Insert new access node above join node 
+		PlanNode newAccess = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+		newAccess.setProperty(NodeConstants.Info.MODEL_ID, modelID);
+		newAccess.addGroups(rightAccess.getGroups());
+		newAccess.addGroups(leftAccess.getGroups());
+        
+        // Combine hints if necessary
+        Object leftHint = leftAccess.getProperty(NodeConstants.Info.MAKE_DEP);
+        if(leftHint != null) {
+            newAccess.setProperty(NodeConstants.Info.MAKE_DEP, leftHint);
+        } else {
+            Object rightHint = rightAccess.getProperty(NodeConstants.Info.MAKE_DEP);
+            if(rightHint != null) {
+                newAccess.setProperty(NodeConstants.Info.MAKE_DEP, rightHint);
+            }    
+        }
+        RulePlaceAccess.copyDependentHints(leftAccess, newAccess);
+        RulePlaceAccess.copyDependentHints(rightAccess, newAccess);
+        RulePlaceAccess.copyDependentHints(joinNode, newAccess);
+        
+        if (insert) {
+            joinNode.addAsParent(newAccess);
+        } else {
+            newAccess.addFirstChild(joinNode);
+        }
+        
+        return newAccess;
+	}
+
+    /**
+     * Get modelID for Access node and cache the result in the Access node.
+     * @param accessNode Access node
+     * @param metadata Metadata access
+     * @return Object Model ID or null if not found.
+     * @throws QueryMetadataException
+     * @throws TeiidComponentException
+     */
+    static Object getModelIDFromAccess(PlanNode accessNode, QueryMetadataInterface metadata) 
+    throws QueryMetadataException, TeiidComponentException {
+
+        Object accessModelID = accessNode.getProperty(NodeConstants.Info.MODEL_ID);
+        if(accessModelID == null) {
+            GroupSymbol group = accessNode.getGroups().iterator().next();
+            if(metadata.isVirtualGroup(group.getMetadataID())) {
+                return null;
+            }
+            accessModelID = metadata.getModelID(group.getMetadataID());
+    
+            accessNode.setProperty(NodeConstants.Info.MODEL_ID, accessModelID);
+        } 
+        
+        return accessModelID;    
+    }
+    
+    private static boolean canRaiseOverSetQuery(PlanNode setOpNode,
+                                     QueryMetadataInterface metadata,
+                                     CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException {
+        
+        Object modelID = null;
+        
+        for (PlanNode childNode : setOpNode.getChildren()) {
+            if(childNode.getType() != NodeConstants.Types.ACCESS) {
+                return false;
+            } 
+            
+            if (FrameUtil.getNonQueryCommand(childNode) != null || FrameUtil.getNestedPlan(childNode) != null) {
+                return false;
+            }
+            
+            // Get model and check that it exists
+            Object accessModelID = getModelIDFromAccess(childNode, metadata);
+            if(accessModelID == null) {
+                return false;
+            }
+            
+            // Reconcile this access node's model ID with existing                                             
+            if(modelID == null) {
+                modelID = accessModelID;
+                
+                if(! CapabilitiesUtil.supportsSetOp(accessModelID, (Operation)setOpNode.getProperty(NodeConstants.Info.SET_OPERATION), metadata, capFinder)) {
+                    return false;
+                }
+            } else if(!CapabilitiesUtil.isSameConnector(modelID, accessModelID, metadata, capFinder)) {
+                return false;
+            }      
+            if (!setOpNode.hasBooleanProperty(NodeConstants.Info.USE_ALL) 
+            		&&  !CapabilitiesUtil.checkElementsAreSearchable((List)NodeEditor.findNodePreOrder(childNode, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS), metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
+            	return false;
+            }
+
+        }
+        return true;
+    }
+    
+	public String toString() {
+		return "RaiseAccess"; //$NON-NLS-1$
+	}
+	
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/parser/QueryParser.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/query/parser/QueryParser.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/parser/QueryParser.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,224 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.parser;
-
-import java.io.StringReader;
-
-import org.teiid.api.exception.query.QueryParserException;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.symbol.Expression;
-
-/**
- * <p>Converts a SQL-string to an object version of a query.  This
- * QueryParser can be reused but is NOT thread-safe as the parser uses an
- * input stream.  Putting multiple queries into the same stream will result
- * in unpredictable and most likely incorrect behavior.</p>
- */
-public class QueryParser {
-    
-    private static ThreadLocal<QueryParser> QUERY_PARSER = new ThreadLocal<QueryParser>() {
-        /** 
-         * @see java.lang.ThreadLocal#initialValue()
-         */
-        @Override
-        protected QueryParser initialValue() {
-            return new QueryParser();
-        }
-    };
-
-	// Used in parsing TokenMgrError message
-	private static final String LINE_MARKER = "line "; //$NON-NLS-1$
-	private static final String COL_MARKER = "column "; //$NON-NLS-1$
-    
-    private static final String XQUERY_DECLARE = "declare"; //$NON-NLS-1$
-    private static final String XML_OPEN_BRACKET = "<"; //$NON-NLS-1$
-
-	private SQLParser parser;
-    
-	/**
-	 * Construct a QueryParser - this may be reused.
-	 */
-	public QueryParser() {}
-    
-    public static QueryParser getQueryParser() {
-        return QUERY_PARSER.get();
-    }
-	
-	/**
-	 * Helper method to get a SQLParser instace for given sql string.
-	 */
-	private SQLParser getSqlParser(String sql) {
-		sql = sql != null ? sql : "";  //$NON-NLS-1$
-		if(parser == null) {
-			parser = new SQLParser(new StringReader(sql));
-		} else {
-			parser.ReInit(new StringReader(sql));	
-		}
-		return parser;		
-	}
-
-	/**
-	 * Takes a SQL string representing a Command and returns the object
-	 * representation.
-	 * @param sql SQL string 
-	 * instead of string litral
-	 * @return SQL object representation
-	 * @throws QueryParserException if parsing fails
-	 * @throws IllegalArgumentException if sql is null
-	 */	
-	public Command parseCommand(String sql) throws QueryParserException {
-	    return parseCommand(sql, new ParseInfo());
-	}
-	
-	/**
-	 * Takes a SQL string representing a Command and returns the object
-	 * representation.
-	 * @param sql SQL string
-	 * @param parseInfo - instructions to parse
-	 * @return SQL object representation
-	 * @throws QueryParserException if parsing fails
-	 * @throws IllegalArgumentException if sql is null
-	 */
-	public Command parseCommand(String sql, ParseInfo parseInfo) throws QueryParserException {
-        if(sql == null || sql.length() == 0) {
-            throw new QueryParserException(QueryPlugin.Util.getString("QueryParser.emptysql")); //$NON-NLS-1$
-        }
-        
-    	Command result = null;
-        try{
-            result = getSqlParser(sql).command(parseInfo);
-            result.setCacheHint(SQLParserUtil.getQueryCacheOption(sql));
-        } catch(ParseException pe) {
-        	if(sql.startsWith(XML_OPEN_BRACKET) || sql.startsWith(XQUERY_DECLARE)) {
-            	throw new QueryParserException(pe, QueryPlugin.Util.getString("QueryParser.xqueryCompilation", sql)); //$NON-NLS-1$
-            }
-            throw convertParserException(pe);
-        } catch(TokenMgrError tme) {
-        	if(sql.startsWith(XML_OPEN_BRACKET) || sql.startsWith(XQUERY_DECLARE)) {
-            	throw new QueryParserException(tme, QueryPlugin.Util.getString("QueryParser.xqueryCompilation", sql)); //$NON-NLS-1$
-            }
-            handleTokenMgrError(tme);
-        }
-		return result;
-	}
-
-    /**
-     * Takes a SQL string representing an SQL criteria (i.e. just the WHERE
-     * clause) and returns the object representation.
-     * @param sql SQL criteria (WHERE clause) string
-     * @return Criteria SQL object representation
-     * @throws QueryParserException if parsing fails
-     * @throws IllegalArgumentException if sql is null
-     */
-    public Criteria parseCriteria(String sql) throws QueryParserException {
-        if(sql == null) {
-            throw new IllegalArgumentException(QueryPlugin.Util.getString("QueryParser.nullSqlCrit")); //$NON-NLS-1$
-        }
-
-        ParseInfo dummyInfo = new ParseInfo();
-
-        Criteria result = null;
-        try{
-            result = getSqlParser(sql).criteria(dummyInfo);
-
-        } catch(ParseException pe) {
-            throw convertParserException(pe);
-
-        } catch(TokenMgrError tme) {
-            handleTokenMgrError(tme);
-        }
-        return result;
-    }
-
-    private QueryParserException convertParserException(ParseException pe) {
-        return new QueryParserException(QueryPlugin.Util.getString("QueryParser.parsingError", pe.getMessage())); //$NON-NLS-1$                        
-    }
-
-    /**
-     * Takes a SQL string representing an SQL expression
-     * and returns the object representation.
-     * @param sql SQL expression string
-     * @return SQL expression object
-     * @throws QueryParserException if parsing fails
-     * @throws IllegalArgumentException if sql is null
-     */
-    public Expression parseExpression(String sql) throws QueryParserException {
-        if(sql == null) {
-            throw new IllegalArgumentException(QueryPlugin.Util.getString("QueryParser.nullSqlExpr")); //$NON-NLS-1$
-        }
-
-        ParseInfo dummyInfo = new ParseInfo();
-
-        Expression result = null;
-        try{
-            result = getSqlParser(sql).expression(dummyInfo);
-
-        } catch(ParseException pe) {
-            throw convertParserException(pe);
-
-        } catch(TokenMgrError tme) {
-            handleTokenMgrError(tme);
-        }
-        return result;
-    }
-
-    private void handleTokenMgrError(TokenMgrError tme) throws QueryParserException{
-//            LogManager.logError( LogConstants.CTX_QUERY_PARSER, tme, new Object[] {"Exception parsing: ", sql} );
-
-        try {
-            // From TokenMgrError, here is format of lexical error:
-            //
-            // "Lexical error at line " + errorLine + ", column " + errorColumn +
-            // ".  Encountered: " + (EOFSeen ? "<EOF> " : ("\"" +
-            // addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
-            // "after : \"" + addEscapes(errorAfter) + "\""
-
-            String msg = tme.getMessage();
-            int index = msg.indexOf(LINE_MARKER);
-            if(index > 0) {
-                index += LINE_MARKER.length();
-                int lastIndex = msg.indexOf(",", index); //$NON-NLS-1$
-                
-                index = msg.indexOf(COL_MARKER, lastIndex);
-                if(index > 0) {
-                    index += COL_MARKER.length();
-                    lastIndex = msg.indexOf(".", index); //$NON-NLS-1$
-                    
-                    QueryParserException qpe = new QueryParserException(QueryPlugin.Util.getString("QueryParser.lexicalError", tme.getMessage())); //$NON-NLS-1$
-                    throw qpe;
-                }
-
-            }
-
-        } catch(QueryParserException e) {
-            throw e;
-        } catch(Throwable e) {
-            throw new QueryParserException(e, e.getMessage());
-        }
-
-        throw new QueryParserException(QueryPlugin.Util.getString("QueryParser.parsingError", tme.getMessage())); //$NON-NLS-1$
-    }
-
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/parser/QueryParser.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/query/parser/QueryParser.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/parser/QueryParser.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/parser/QueryParser.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,232 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.parser;
+
+import java.io.StringReader;
+
+import org.teiid.api.exception.query.QueryParserException;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.sql.lang.CacheHint;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.symbol.Expression;
+
+/**
+ * <p>Converts a SQL-string to an object version of a query.  This
+ * QueryParser can be reused but is NOT thread-safe as the parser uses an
+ * input stream.  Putting multiple queries into the same stream will result
+ * in unpredictable and most likely incorrect behavior.</p>
+ */
+public class QueryParser {
+    
+    private static ThreadLocal<QueryParser> QUERY_PARSER = new ThreadLocal<QueryParser>() {
+        /** 
+         * @see java.lang.ThreadLocal#initialValue()
+         */
+        @Override
+        protected QueryParser initialValue() {
+            return new QueryParser();
+        }
+    };
+
+	// Used in parsing TokenMgrError message
+	private static final String LINE_MARKER = "line "; //$NON-NLS-1$
+	private static final String COL_MARKER = "column "; //$NON-NLS-1$
+    
+    private static final String XQUERY_DECLARE = "declare"; //$NON-NLS-1$
+    private static final String XML_OPEN_BRACKET = "<"; //$NON-NLS-1$
+
+	private SQLParser parser;
+    
+	/**
+	 * Construct a QueryParser - this may be reused.
+	 */
+	public QueryParser() {}
+    
+    public static QueryParser getQueryParser() {
+        return QUERY_PARSER.get();
+    }
+	
+	/**
+	 * Helper method to get a SQLParser instace for given sql string.
+	 */
+	private SQLParser getSqlParser(String sql) {
+		sql = sql != null ? sql : "";  //$NON-NLS-1$
+		if(parser == null) {
+			parser = new SQLParser(new StringReader(sql));
+		} else {
+			parser.ReInit(new StringReader(sql));	
+		}
+		return parser;		
+	}
+
+	/**
+	 * Takes a SQL string representing a Command and returns the object
+	 * representation.
+	 * @param sql SQL string 
+	 * instead of string litral
+	 * @return SQL object representation
+	 * @throws QueryParserException if parsing fails
+	 * @throws IllegalArgumentException if sql is null
+	 */	
+	public Command parseCommand(String sql) throws QueryParserException {
+	    return parseCommand(sql, new ParseInfo());
+	}
+	
+	/**
+	 * Takes a SQL string representing a Command and returns the object
+	 * representation.
+	 * @param sql SQL string
+	 * @param parseInfo - instructions to parse
+	 * @return SQL object representation
+	 * @throws QueryParserException if parsing fails
+	 * @throws IllegalArgumentException if sql is null
+	 */
+	public Command parseCommand(String sql, ParseInfo parseInfo) throws QueryParserException {
+        if(sql == null || sql.length() == 0) {
+            throw new QueryParserException(QueryPlugin.Util.getString("QueryParser.emptysql")); //$NON-NLS-1$
+        }
+        
+    	Command result = null;
+        try{
+            result = getSqlParser(sql).command(parseInfo);
+            result.setCacheHint(SQLParserUtil.getQueryCacheOption(sql));
+        } catch(ParseException pe) {
+        	if(sql.startsWith(XML_OPEN_BRACKET) || sql.startsWith(XQUERY_DECLARE)) {
+            	throw new QueryParserException(pe, QueryPlugin.Util.getString("QueryParser.xqueryCompilation", sql)); //$NON-NLS-1$
+            }
+            throw convertParserException(pe);
+        } catch(TokenMgrError tme) {
+        	if(sql.startsWith(XML_OPEN_BRACKET) || sql.startsWith(XQUERY_DECLARE)) {
+            	throw new QueryParserException(tme, QueryPlugin.Util.getString("QueryParser.xqueryCompilation", sql)); //$NON-NLS-1$
+            }
+            handleTokenMgrError(tme);
+        }
+		return result;
+	}
+	
+	public CacheHint parseCacheHint(String sql) throws QueryParserException {
+        if(sql == null || sql.length() == 0) {
+            throw new QueryParserException(QueryPlugin.Util.getString("QueryParser.emptysql")); //$NON-NLS-1$
+        }        
+        return SQLParserUtil.getQueryCacheOption(sql);        
+	}	
+
+    /**
+     * Takes a SQL string representing an SQL criteria (i.e. just the WHERE
+     * clause) and returns the object representation.
+     * @param sql SQL criteria (WHERE clause) string
+     * @return Criteria SQL object representation
+     * @throws QueryParserException if parsing fails
+     * @throws IllegalArgumentException if sql is null
+     */
+    public Criteria parseCriteria(String sql) throws QueryParserException {
+        if(sql == null) {
+            throw new IllegalArgumentException(QueryPlugin.Util.getString("QueryParser.nullSqlCrit")); //$NON-NLS-1$
+        }
+
+        ParseInfo dummyInfo = new ParseInfo();
+
+        Criteria result = null;
+        try{
+            result = getSqlParser(sql).criteria(dummyInfo);
+
+        } catch(ParseException pe) {
+            throw convertParserException(pe);
+
+        } catch(TokenMgrError tme) {
+            handleTokenMgrError(tme);
+        }
+        return result;
+    }
+
+    private QueryParserException convertParserException(ParseException pe) {
+        return new QueryParserException(QueryPlugin.Util.getString("QueryParser.parsingError", pe.getMessage())); //$NON-NLS-1$                        
+    }
+
+    /**
+     * Takes a SQL string representing an SQL expression
+     * and returns the object representation.
+     * @param sql SQL expression string
+     * @return SQL expression object
+     * @throws QueryParserException if parsing fails
+     * @throws IllegalArgumentException if sql is null
+     */
+    public Expression parseExpression(String sql) throws QueryParserException {
+        if(sql == null) {
+            throw new IllegalArgumentException(QueryPlugin.Util.getString("QueryParser.nullSqlExpr")); //$NON-NLS-1$
+        }
+
+        ParseInfo dummyInfo = new ParseInfo();
+
+        Expression result = null;
+        try{
+            result = getSqlParser(sql).expression(dummyInfo);
+
+        } catch(ParseException pe) {
+            throw convertParserException(pe);
+
+        } catch(TokenMgrError tme) {
+            handleTokenMgrError(tme);
+        }
+        return result;
+    }
+
+    private void handleTokenMgrError(TokenMgrError tme) throws QueryParserException{
+//            LogManager.logError( LogConstants.CTX_QUERY_PARSER, tme, new Object[] {"Exception parsing: ", sql} );
+
+        try {
+            // From TokenMgrError, here is format of lexical error:
+            //
+            // "Lexical error at line " + errorLine + ", column " + errorColumn +
+            // ".  Encountered: " + (EOFSeen ? "<EOF> " : ("\"" +
+            // addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
+            // "after : \"" + addEscapes(errorAfter) + "\""
+
+            String msg = tme.getMessage();
+            int index = msg.indexOf(LINE_MARKER);
+            if(index > 0) {
+                index += LINE_MARKER.length();
+                int lastIndex = msg.indexOf(",", index); //$NON-NLS-1$
+                
+                index = msg.indexOf(COL_MARKER, lastIndex);
+                if(index > 0) {
+                    index += COL_MARKER.length();
+                    lastIndex = msg.indexOf(".", index); //$NON-NLS-1$
+                    
+                    QueryParserException qpe = new QueryParserException(QueryPlugin.Util.getString("QueryParser.lexicalError", tme.getMessage())); //$NON-NLS-1$
+                    throw qpe;
+                }
+
+            }
+
+        } catch(QueryParserException e) {
+            throw e;
+        } catch(Throwable e) {
+            throw new QueryParserException(e, e.getMessage());
+        }
+
+        throw new QueryParserException(QueryPlugin.Util.getString("QueryParser.parsingError", tme.getMessage())); //$NON-NLS-1$
+    }
+
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,2531 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.rewriter;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.sql.Date;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.TreeSet;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.FunctionExecutionException;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.Assertion;
-import org.teiid.core.util.TimestampWithTimezone;
-import org.teiid.language.SQLConstants.NonReserved;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.FunctionMethods;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.processor.relational.DependentValueSource;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.resolver.util.ResolverVisitor;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.ProcedureReservedWords;
-import org.teiid.query.sql.LanguageObject.Util;
-import org.teiid.query.sql.lang.AbstractSetCriteria;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-import org.teiid.query.sql.lang.BetweenCriteria;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.ExpressionCriteria;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.GroupBy;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.Into;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.JoinPredicate;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.Limit;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.NotCriteria;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.OrderByItem;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetClause;
-import org.teiid.query.sql.lang.SetClauseList;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.TextTable;
-import org.teiid.query.sql.lang.TranslatableProcedureContainer;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.lang.WithQueryCommand;
-import org.teiid.query.sql.lang.XMLTable;
-import org.teiid.query.sql.lang.PredicateCriteria.Negatable;
-import org.teiid.query.sql.navigator.PostOrderNavigator;
-import org.teiid.query.sql.navigator.PreOrderNavigator;
-import org.teiid.query.sql.proc.Block;
-import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-import org.teiid.query.sql.proc.CriteriaSelector;
-import org.teiid.query.sql.proc.ExpressionStatement;
-import org.teiid.query.sql.proc.HasCriteria;
-import org.teiid.query.sql.proc.IfStatement;
-import org.teiid.query.sql.proc.LoopStatement;
-import org.teiid.query.sql.proc.Statement;
-import org.teiid.query.sql.proc.TranslateCriteria;
-import org.teiid.query.sql.proc.WhileStatement;
-import org.teiid.query.sql.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.CaseExpression;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.ExpressionSymbol;
-import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.ScalarSubquery;
-import org.teiid.query.sql.symbol.SearchedCaseExpression;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.symbol.AggregateSymbol.Type;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.util.ValueIterator;
-import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
-import org.teiid.query.sql.visitor.CriteriaTranslatorVisitor;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.EvaluatableVisitor;
-import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
-import org.teiid.query.sql.visitor.PredicateCollectorVisitor;
-import org.teiid.query.sql.visitor.EvaluatableVisitor.EvaluationLevel;
-import org.teiid.query.util.CommandContext;
-import org.teiid.translator.SourceSystemFunctions;
-
-
-/**
- * Rewrites commands and command fragments to a form that is better for planning and execution.  There is a current limitation that
- * command objects themselves cannot change type, since the same object is always used. 
- */
-public class QueryRewriter {
-
-    public static final CompareCriteria TRUE_CRITERIA = new CompareCriteria(new Constant(new Integer(1), DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, new Constant(new Integer(1), DataTypeManager.DefaultDataClasses.INTEGER));
-    public static final CompareCriteria FALSE_CRITERIA = new CompareCriteria(new Constant(new Integer(1), DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, new Constant(new Integer(0), DataTypeManager.DefaultDataClasses.INTEGER));
-    public static final CompareCriteria UNKNOWN_CRITERIA = new CompareCriteria(new Constant(null, DataTypeManager.DefaultDataClasses.STRING), CompareCriteria.NE, new Constant(null, DataTypeManager.DefaultDataClasses.STRING));
-    
-    private static final Map<String, String> ALIASED_FUNCTIONS = new HashMap<String, String>();
-    
-    static {
-    	ALIASED_FUNCTIONS.put("lower", SourceSystemFunctions.LCASE); //$NON-NLS-1$
-    	ALIASED_FUNCTIONS.put("upper", SourceSystemFunctions.UCASE); //$NON-NLS-1$
-    	ALIASED_FUNCTIONS.put("cast", SourceSystemFunctions.CONVERT); //$NON-NLS-1$
-    	ALIASED_FUNCTIONS.put("nvl", SourceSystemFunctions.IFNULL); //$NON-NLS-1$
-    	ALIASED_FUNCTIONS.put("||", SourceSystemFunctions.CONCAT); //$NON-NLS-1$
-    	ALIASED_FUNCTIONS.put("chr", SourceSystemFunctions.CHAR); //$NON-NLS-1$
-    }
-    
-    private QueryMetadataInterface metadata;
-    private CommandContext context;
-    private CreateUpdateProcedureCommand procCommand;
-    
-    private boolean rewriteSubcommands;
-    private boolean processing;
-    private Evaluator evaluator;
-    private Map variables; //constant propagation
-    private int commandType;
-    
-    private QueryRewriter(QueryMetadataInterface metadata,
-			CommandContext context, CreateUpdateProcedureCommand procCommand) {
-		this.metadata = metadata;
-		this.context = context;
-		this.procCommand = procCommand;
-		this.evaluator = new Evaluator(Collections.emptyMap(), null, context);
-	}
-    
-    public static Command evaluateAndRewrite(Command command, Evaluator eval, CommandContext context, QueryMetadataInterface metadata) throws TeiidProcessingException, TeiidComponentException {
-    	QueryRewriter queryRewriter = new QueryRewriter(metadata, context, null);
-    	queryRewriter.evaluator = eval;
-    	queryRewriter.rewriteSubcommands = true;
-    	queryRewriter.processing = true;
-		return queryRewriter.rewriteCommand(command, false);
-    }
-
-	public static Command rewrite(Command command, CreateUpdateProcedureCommand procCommand, QueryMetadataInterface metadata, CommandContext context, Map variableValues, int commandType) throws TeiidComponentException, TeiidProcessingException{
-		QueryRewriter rewriter = new QueryRewriter(metadata, context, procCommand);
-		rewriter.rewriteSubcommands = true;
-		rewriter.variables = variableValues;
-		rewriter.commandType = commandType;
-		return rewriter.rewriteCommand(command, false);
-	}
-    
-	public static Command rewrite(Command command, QueryMetadataInterface metadata, CommandContext context) throws TeiidComponentException, TeiidProcessingException{
-		return rewrite(command, null, metadata, context, null, Command.TYPE_UNKNOWN);
-    }
-
-    /**
-     * Rewrites the command and all of its subcommands (both embedded and non-embedded)
-     *  
-     * @param command
-     * @param removeOrderBy
-     * @return
-     * @throws QueryValidatorException
-     */
-	private Command rewriteCommand(Command command, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
-		QueryMetadataInterface oldMetadata = metadata;
-		CreateUpdateProcedureCommand oldProcCommand = procCommand;
-        
-		Map tempMetadata = command.getTemporaryMetadata();
-        if(tempMetadata != null) {
-        	metadata = new TempMetadataAdapter(metadata, new TempMetadataStore(tempMetadata));
-        }
-        
-        switch(command.getType()) {
-			case Command.TYPE_QUERY:
-                QueryCommand queryCommand = (QueryCommand)command;
-            	if (removeOrderBy && queryCommand.getLimit() == null) {
-            		queryCommand.setOrderBy(null);
-                }
-            	if (queryCommand.getWith() != null) {
-            		for (WithQueryCommand withQueryCommand : queryCommand.getWith()) {
-            			if (withQueryCommand.getColumns() == null) {
-            				List<ElementSymbol> columns = ResolverUtil.resolveElementsInGroup(withQueryCommand.getGroupSymbol(), metadata);
-            				withQueryCommand.setColumns(LanguageObject.Util.deepClone(columns, ElementSymbol.class));
-            			}
-						rewriteSubqueryContainer(withQueryCommand, true);
-					}
-            	}
-                if(command instanceof Query) {
-                    command = rewriteQuery((Query) command);
-                }else {
-                    command = rewriteSetQuery((SetQuery) command);
-                }
-                break;
-            case Command.TYPE_STORED_PROCEDURE:
-                command = rewriteExec((StoredProcedure) command);
-                break;
-    		case Command.TYPE_INSERT:
-                command = rewriteInsert((Insert) command);
-                break;
-			case Command.TYPE_UPDATE:
-                command = rewriteUpdate((Update) command);
-                break;
-			case Command.TYPE_DELETE:
-                command = rewriteDelete((Delete) command);
-                break;
-            case Command.TYPE_UPDATE_PROCEDURE:
-                procCommand = (CreateUpdateProcedureCommand) command;
-                command = rewriteUpdateProcedure((CreateUpdateProcedureCommand) command);
-                break;
-            case Command.TYPE_BATCHED_UPDATE:
-            	List subCommands = ((BatchedUpdateCommand)command).getUpdateCommands();
-                for (int i = 0; i < subCommands.size(); i++) {
-                    Command subCommand = (Command)subCommands.get(i);
-                    subCommand = rewriteCommand(subCommand, false);
-                    subCommands.set(i, subCommand);
-                }
-                break;
-            	
-		}
-        
-        this.metadata = oldMetadata;
-        this.procCommand = oldProcCommand;
-        return command;
-	}
-    
-	private Command rewriteUpdateProcedure(CreateUpdateProcedureCommand command)
-								 throws TeiidComponentException, TeiidProcessingException{
-        Map oldVariables = variables;
-    	if (command.getUserCommand() != null) {
-            variables = QueryResolver.getVariableValues(command.getUserCommand(), metadata);                        
-            commandType = command.getUserCommand().getType();
-    	}
-
-		Block block = rewriteBlock(command.getBlock());
-        command.setBlock(block);
-
-        variables = oldVariables;
-        
-        return command;
-	}
-
-	private Block rewriteBlock(Block block)
-								 throws TeiidComponentException, TeiidProcessingException{
-		List statements = block.getStatements();
-        Iterator stmtIter = statements.iterator();
-
-		List newStmts = new ArrayList(statements.size());
-		// plan each statement in the block
-        while(stmtIter.hasNext()) {
-			Statement stmnt = (Statement) stmtIter.next();
-			Object newStmt = rewriteStatement(stmnt);
-			if(newStmt instanceof Statement) {
-				newStmts.add(newStmt);
-			} else if (newStmt instanceof List) {
-			    newStmts.addAll((List)newStmt);
-            }
-        }
-
-        block.setStatements(newStmts);
-
-        return block;
-	 }
-
-	private Object rewriteStatement(Statement statement)
-								 throws TeiidComponentException, TeiidProcessingException{
-
-        // evaluate the HAS Criteria on the procedure and rewrite
-		int stmtType = statement.getType();
-		switch(stmtType) {
-			case Statement.TYPE_IF:
-				IfStatement ifStmt = (IfStatement) statement;
-				Criteria ifCrit = ifStmt.getCondition();
-				Criteria evalCrit = rewriteCriteria(ifCrit);
-                
-				ifStmt.setCondition(evalCrit);
-				if(evalCrit.equals(TRUE_CRITERIA)) {
-					Block ifblock = rewriteBlock(ifStmt.getIfBlock());
-					return ifblock.getStatements();
-				} else if(evalCrit.equals(FALSE_CRITERIA) || evalCrit.equals(UNKNOWN_CRITERIA)) {
-					if(ifStmt.hasElseBlock()) {
-						Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
-						return elseBlock.getStatements();
-					} 
-                    return null;
-				} else {
-					Block ifblock = rewriteBlock(ifStmt.getIfBlock());
-					ifStmt.setIfBlock(ifblock);
-					if(ifStmt.hasElseBlock()) {
-						Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
-						ifStmt.setElseBlock(elseBlock);
-					}
-				}
-				return ifStmt;
-            case Statement.TYPE_ERROR: 
-            case Statement.TYPE_DECLARE:
-            case Statement.TYPE_ASSIGNMENT:
-				ExpressionStatement exprStmt = (ExpressionStatement) statement;
-				// replace variables to references, these references are later
-				// replaced in the processor with variable values
-				Expression expr = exprStmt.getExpression();
-				if (expr != null) {
-					expr = rewriteExpressionDirect(expr);
-	                exprStmt.setExpression(expr);
-				}
-				return exprStmt;
-            case Statement.TYPE_COMMAND:
-				CommandStatement cmdStmt = (CommandStatement) statement;
-                rewriteSubqueryContainer(cmdStmt, false);
-                
-				if(cmdStmt.getCommand().getType() == Command.TYPE_UPDATE) {
-                    Update update = (Update)cmdStmt.getCommand();
-                    if (update.getChangeList().isEmpty()) {
-                        return null;
-                    }
-				}
-                return statement;
-            case Statement.TYPE_LOOP: 
-                LoopStatement loop = (LoopStatement)statement; 
-                
-                rewriteSubqueryContainer(loop, false);
-                
-                rewriteBlock(loop.getBlock());
-                
-                if (loop.getBlock().getStatements().isEmpty()) {
-                    return null;
-                }
-                
-                return loop;
-            case Statement.TYPE_WHILE:
-                WhileStatement whileStatement = (WhileStatement) statement;
-                Criteria crit = whileStatement.getCondition();
-                crit = rewriteCriteria(crit);
-                
-                whileStatement.setCondition(crit);
-                if(crit.equals(TRUE_CRITERIA)) {
-                    throw new QueryValidatorException(QueryPlugin.Util.getString("QueryRewriter.infinite_while")); //$NON-NLS-1$
-                } else if(crit.equals(FALSE_CRITERIA) || crit.equals(UNKNOWN_CRITERIA)) {
-                    return null;
-                } 
-                whileStatement.setBlock(rewriteBlock(whileStatement.getBlock()));
-                
-                if (whileStatement.getBlock().getStatements().isEmpty()) {
-                    return null;
-                }
-                
-                return whileStatement;
-			default:
-				return statement;
-		}
-	}
-    
-    /** 
-     * @param removeOrderBy
-     * @param assStmt
-     * @throws QueryValidatorException
-     */
-    private void rewriteSubqueryContainer(SubqueryContainer container, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
-        if (rewriteSubcommands && container.getCommand() != null && container.getCommand().getProcessorPlan() == null) {
-        	container.setCommand(rewriteCommand(container.getCommand(), removeOrderBy));
-        }
-    }
-    
-	/**
-	 * <p>The HasCriteria evaluates to a TRUE_CRITERIA or a FALSE_CRITERIA, it checks to see
-	 * if type of criteria on the elements specified by the CriteriaSelector is specified on
-	 * the user's command.</p>
-	 */
-	private Criteria rewriteCriteria(HasCriteria hasCrit) {
-		Criteria userCrit = null;
-		Command userCommand = procCommand.getUserCommand();
-		int cmdType = userCommand.getType();
-		switch(cmdType) {
-			case Command.TYPE_DELETE:
-				userCrit = ((Delete)userCommand).getCriteria();
-				break;
-			case Command.TYPE_UPDATE:
-				userCrit = ((Update)userCommand).getCriteria();
-				break;
-			default:
-				return FALSE_CRITERIA;
-		}
-
-		if(userCrit == null) {
-			return FALSE_CRITERIA;
-		}
-
-		// get the CriteriaSelector, elements on the selector and the selector type
-		CriteriaSelector selector = hasCrit.getSelector();
-
-		Collection hasCritElmts = null;
-		if(selector.hasElements()) {
-			hasCritElmts = selector.getElements();
-			// collect elements present on the user's criteria and check if
-			// all of the hasCriteria elements are among them
-			Collection<ElementSymbol> userElmnts = ElementCollectorVisitor.getElements(userCrit, true);
-			if(!userElmnts.containsAll(hasCritElmts)) {
-				return FALSE_CRITERIA;
-			}
-		}
-
-		int selectorType = selector.getSelectorType();
-		// if no selector type specified return true
-		// already checked all HAS elements present on user criteria
-		if(selectorType == CriteriaSelector.NO_TYPE) {
-			return TRUE_CRITERIA;
-		}
-
-		// collect all predicate criteria present on the user's criteria
-    	Iterator criteriaIter = PredicateCollectorVisitor.getPredicates(userCrit).iterator();
-    	while(criteriaIter.hasNext()) {
-    		Criteria predicateCriteria = (Criteria) criteriaIter.next();
-    		// atleast one of the hasElemnets should be on this predicate else
-    		// proceed to the next predicate
-			Collection<ElementSymbol> predElmnts = ElementCollectorVisitor.getElements(predicateCriteria, true);
-			if(selector.hasElements()) {
-				Iterator hasIter = hasCritElmts.iterator();
-				boolean containsElmnt = false;
-				while(hasIter.hasNext()) {
-					ElementSymbol hasElmnt = (ElementSymbol) hasIter.next();
-					if(predElmnts.contains(hasElmnt)) {
-						containsElmnt = true;
-					}
-				}
-
-				if(!containsElmnt) {
-					continue;
-				}
-			}
-
-			// check if the predicate criteria type maches the type specified
-			// by the criteria selector
-    		switch(selectorType) {
-	    		case CriteriaSelector.IN:
-		    		if(predicateCriteria instanceof SetCriteria) {
-	    				return TRUE_CRITERIA;
-		    		}
-                    break;
-	    		case CriteriaSelector.LIKE:
-		    		if(predicateCriteria instanceof MatchCriteria) {
-	    				return TRUE_CRITERIA;
-		    		}
-                    break;
-                case CriteriaSelector.IS_NULL:
-                    if(predicateCriteria instanceof IsNullCriteria) {
-                        return TRUE_CRITERIA;
-                    }
-                    break;
-                case CriteriaSelector.BETWEEN:
-                    if(predicateCriteria instanceof BetweenCriteria) {
-                        return TRUE_CRITERIA;
-                    }
-                    break;
-	    		default: // EQ, GT, LT, GE, LE criteria
-		    		if(predicateCriteria instanceof CompareCriteria) {
-		    			CompareCriteria compCrit = (CompareCriteria) predicateCriteria;
-		    			if(compCrit.getOperator() == selectorType) {
-		    				return TRUE_CRITERIA;
-		    			}
-		    		}
-                    break;
-			}
-		}
-
-		return FALSE_CRITERIA;
-	}
-
-	/**
-	 * <p>TranslateCriteria is evaluated by translating elements on parts(restricted by the type
-	 * of criteria and elements specified on the CriteriaSelector) the user's criteria
-	 * using the translations provided on the TranslateCriteria and symbol mapping between
-	 * virtual group elements and the expressions on the query transformation defining the
-	 * virtual group.</p>
-	 */
-	private Criteria rewriteCriteria(TranslateCriteria transCrit)
-			 throws TeiidComponentException, TeiidProcessingException{
-
-		// criteria translated
-		Criteria translatedCriteria = null;
-
-		// get the user's command from the procedure
-		Command userCmd = procCommand.getUserCommand();
-
-		if (!(userCmd instanceof TranslatableProcedureContainer)) {
-			return FALSE_CRITERIA;
-		}
-
-		Criteria userCriteria = ((TranslatableProcedureContainer)userCmd).getCriteria();
-
-		if(userCriteria == null) {
-			return FALSE_CRITERIA;
-		}
-
-		// get the symbolmap between virtual elements and theie counterpart expressions
-		// from the virtual group's query transform
-		CriteriaTranslatorVisitor translateVisitor = new CriteriaTranslatorVisitor(procCommand.getSymbolMap());
-
-		// check if there is a CriteriaSelector specified to restrict
-		// parts of user's criteria to be translated
-		// get the CriteriaSelector, elements on the selector and the selector type
-		CriteriaSelector selector = transCrit.getSelector();
-		HasCriteria hasCrit = new HasCriteria(selector);
-
-		// base on the selector evaluate Has criteria, if false
-		// return a false criteria
-		Criteria result = rewriteCriteria(hasCrit);
-
-		if(result.equals(FALSE_CRITERIA)) {
-			return FALSE_CRITERIA;
-		}
-		translateVisitor.setCriteriaSelector(selector);
-		if(transCrit.hasTranslations()) {
-			translateVisitor.setTranslations(transCrit.getTranslations());
-		}
-
-		// create a clone of user's criteria that is then translated
-		Criteria userClone = (Criteria) userCriteria.clone();
-
-		// CriteriaTranslatorVisitor visits the user's criteria
-        PreOrderNavigator.doVisit(userClone, translateVisitor);
-
-		// translated criteria
-		translatedCriteria = translateVisitor.getTranslatedCriteria();
-		((TranslatableProcedureContainer)userCmd).addImplicitParameters(translateVisitor.getImplicitParams());
-		
-		translatedCriteria = rewriteCriteria(translatedCriteria);
-
-		// apply any implicit conversions
-		try {
-            ResolverVisitor.resolveLanguageObject(translatedCriteria, metadata);
-		} catch(TeiidException ex) {
-            throw new QueryValidatorException(ex, "ERR.015.009.0002", QueryPlugin.Util.getString("ERR.015.009.0002", translatedCriteria)); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-
-		return translatedCriteria;
-	}
-
-	private Command rewriteQuery(Query query)
-             throws TeiidComponentException, TeiidProcessingException{
-        
-        // Rewrite from clause
-        From from = query.getFrom();
-        if(from != null){
-            List clauses = new ArrayList(from.getClauses().size());
-            Iterator clauseIter = from.getClauses().iterator();
-            while(clauseIter.hasNext()) {
-                clauses.add( rewriteFromClause(query, (FromClause) clauseIter.next()) );
-            }
-            from.setClauses(clauses);
-        } else {
-            query.setOrderBy(null);
-        }
-
-        // Rewrite criteria
-        Criteria crit = query.getCriteria();
-        if(crit != null) {
-            crit = rewriteCriteria(crit);
-            if(crit == TRUE_CRITERIA) {
-                query.setCriteria(null);
-            } else {
-                query.setCriteria(crit);
-            } 
-        }
-
-        query = rewriteGroupBy(query);
-
-        // Rewrite having
-        Criteria having = query.getHaving();
-        if(having != null) {
-            query.setHaving(rewriteCriteria(having));
-        }
-                
-        rewriteExpressions(query.getSelect());
-
-        if (!query.getIsXML()) {
-            query = (Query)rewriteOrderBy(query);
-        }
-        
-        if (query.getLimit() != null) {
-            query.setLimit(rewriteLimitClause(query.getLimit()));
-        }
-        
-        if (query.getInto() != null) {
-            return rewriteSelectInto(query);
-        }
-        
-        return query;
-    }
-
-	/**
-	 * Converts a group by with expressions into a group by with only element symbols and an inline view
-	 * @param query
-	 * @return
-	 * @throws QueryValidatorException
-	 */
-	private Query rewriteGroupBy(Query query) throws TeiidComponentException, TeiidProcessingException{
-		if (query.getGroupBy() == null) {
-			return query;
-		}
-		if (isDistinctWithGroupBy(query)) {
-			query.getSelect().setDistinct(false);
-		}
-        // we check for group by expressions here to create an ANSI SQL plan
-        boolean hasExpression = false;
-        for (final Iterator iterator = query.getGroupBy().getSymbols().iterator(); !hasExpression && iterator.hasNext();) {
-            hasExpression = iterator.next() instanceof ExpressionSymbol;
-        } 
-        if (!hasExpression) {
-        	return query;
-        }
-        Select select = query.getSelect();
-        GroupBy groupBy = query.getGroupBy();
-        query.setGroupBy(null);
-        Criteria having = query.getHaving();
-        query.setHaving(null);
-        OrderBy orderBy = query.getOrderBy();
-        query.setOrderBy(null);
-        Limit limit = query.getLimit();
-        query.setLimit(null);
-        Into into = query.getInto();
-        query.setInto(null);
-        Set<Expression> newSelectColumns = new HashSet<Expression>();
-        for (final Iterator iterator = groupBy.getSymbols().iterator(); iterator.hasNext();) {
-            newSelectColumns.add(SymbolMap.getExpression((SingleElementSymbol)iterator.next()));
-        }
-        Set<AggregateSymbol> aggs = new HashSet<AggregateSymbol>();
-        aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(select, true));
-        if (having != null) {
-            aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(having, true));
-        }
-        for (AggregateSymbol aggregateSymbol : aggs) {
-            if (aggregateSymbol.getExpression() != null) {
-                Expression expr = aggregateSymbol.getExpression();
-                newSelectColumns.add(SymbolMap.getExpression(expr));
-            }
-        }
-        Select innerSelect = new Select();
-        int index = 0;
-        for (Expression expr : newSelectColumns) {
-            if (expr instanceof SingleElementSymbol) {
-                innerSelect.addSymbol((SingleElementSymbol)expr);
-            } else {
-                innerSelect.addSymbol(new ExpressionSymbol("EXPR" + index++ , expr)); //$NON-NLS-1$
-            }
-        }
-        query.setSelect(innerSelect);
-        Query outerQuery = null;
-        try {
-            outerQuery = QueryRewriter.createInlineViewQuery(new GroupSymbol("X"), query, metadata, query.getSelect().getProjectedSymbols()); //$NON-NLS-1$
-        } catch (TeiidException err) {
-            throw new TeiidRuntimeException(err);
-        }
-        Iterator iter = outerQuery.getSelect().getProjectedSymbols().iterator();
-        HashMap<Expression, SingleElementSymbol> expressionMap = new HashMap<Expression, SingleElementSymbol>();
-        for (SingleElementSymbol symbol : (List<SingleElementSymbol>)query.getSelect().getProjectedSymbols()) {
-            expressionMap.put(SymbolMap.getExpression(symbol), (SingleElementSymbol)iter.next());
-        }
-        ExpressionMappingVisitor.mapExpressions(groupBy, expressionMap);
-        outerQuery.setGroupBy(groupBy);
-        ExpressionMappingVisitor.mapExpressions(having, expressionMap);
-        outerQuery.setHaving(having);
-        ExpressionMappingVisitor.mapExpressions(orderBy, expressionMap);
-        outerQuery.setOrderBy(orderBy);
-        outerQuery.setLimit(limit);
-        ExpressionMappingVisitor.mapExpressions(select, expressionMap);
-        outerQuery.setSelect(select);
-        outerQuery.setInto(into);
-        outerQuery.setOption(query.getOption());
-        query = outerQuery;
-        rewriteExpressions(innerSelect);
-		return query;
-	}
-	
-	public static boolean isDistinctWithGroupBy(Query query) {
-		GroupBy groupBy = query.getGroupBy();
-		if (groupBy == null) {
-			return false;
-		}
-		HashSet<Expression> selectExpressions = new HashSet<Expression>();
-		for (SingleElementSymbol selectExpr : (List<SingleElementSymbol>)query.getSelect().getProjectedSymbols()) {
-			selectExpressions.add(SymbolMap.getExpression(selectExpr));
-		}
-		for (SingleElementSymbol groupByExpr :  (List<SingleElementSymbol>)groupBy.getSymbols()) {
-			if (!selectExpressions.contains(groupByExpr)) {
-				return false;
-			}
-		}
-		return true;
-	}
-    
-    private void rewriteExpressions(LanguageObject obj) throws TeiidComponentException, TeiidProcessingException{
-        if (obj == null) {
-            return;
-        }
-        ExpressionMappingVisitor visitor = new ExpressionMappingVisitor(null) {
-            /** 
-             * @see org.teiid.query.sql.visitor.ExpressionMappingVisitor#replaceExpression(org.teiid.query.sql.symbol.Expression)
-             */
-            @Override
-            public Expression replaceExpression(Expression element) {
-                try {
-                    return rewriteExpressionDirect(element);
-                } catch (TeiidException err) {
-                    throw new TeiidRuntimeException(err);
-                }
-            }
-        };
-        try {
-            PostOrderNavigator.doVisit(obj, visitor);
-        } catch (TeiidRuntimeException err) {
-            if (err.getChild() instanceof TeiidComponentException) {
-                throw (TeiidComponentException)err.getChild();
-            } 
-            if (err.getChild() instanceof TeiidProcessingException) {
-                throw (TeiidProcessingException)err.getChild();
-            } 
-            throw err;
-        }
-    }
-	
-    /**
-     * Rewrite the order by clause.
-     * Unrelated order by expressions will cause the creation of nested inline views.
-     *  
-     * @param query
-     * @throws TeiidComponentException, MetaMatrixProcessingException
-     */
-    public QueryCommand rewriteOrderBy(QueryCommand queryCommand) throws TeiidComponentException {
-    	final OrderBy orderBy = queryCommand.getOrderBy();
-        if (orderBy == null) {
-            return queryCommand;
-        }
-        Select select = queryCommand.getProjectedQuery().getSelect();
-        final List projectedSymbols = select.getProjectedSymbols();
-        
-        LinkedList<OrderByItem> unrelatedItems = new LinkedList<OrderByItem>();
-        
-        boolean hasUnrelatedExpression = rewriteOrderBy(queryCommand, orderBy,
-				projectedSymbols, unrelatedItems);
-        
-        if (orderBy.getVariableCount() == 0 || !hasUnrelatedExpression) {
-        	return queryCommand;
-        } 
-        
-        int originalSymbolCount = select.getProjectedSymbols().size();
-
-        //add unrelated to select
-        for (OrderByItem orderByItem : unrelatedItems) {
-            select.addSymbol(orderByItem.getSymbol());				
-		}
-        makeSelectUnique(select, false);
-        
-        Query query = queryCommand.getProjectedQuery();
-        
-        Into into = query.getInto();
-        query.setInto(null);
-        Limit limit = query.getLimit();
-        query.setLimit(null);
-        query.setOrderBy(null);
-        
-        Query top = null;
-        
-        try {
-        	top = createInlineViewQuery(new GroupSymbol("X"), query, metadata, select.getProjectedSymbols()); //$NON-NLS-1$
-			Iterator iter = top.getSelect().getProjectedSymbols().iterator();
-		    HashMap<Expression, SingleElementSymbol> expressionMap = new HashMap<Expression, SingleElementSymbol>();
-		    for (SingleElementSymbol symbol : (List<SingleElementSymbol>)select.getProjectedSymbols()) {
-		    	SingleElementSymbol ses = (SingleElementSymbol)iter.next();
-		        expressionMap.put(SymbolMap.getExpression(symbol), ses);
-		        expressionMap.put(new ElementSymbol(symbol.getName()), ses);
-		    }
-		    ExpressionMappingVisitor.mapExpressions(orderBy, expressionMap);
-		    //now the order by should only contain element symbols
-		} catch (TeiidException err) {
-            throw new TeiidRuntimeException(err);
-        }
-		List symbols = top.getSelect().getSymbols();
-		top.getSelect().setSymbols(symbols.subList(0, originalSymbolCount));
-		top.setInto(into);
-		top.setLimit(limit);
-		top.setOrderBy(orderBy);
-		return top;
-    }
-
-	public static boolean rewriteOrderBy(QueryCommand queryCommand,
-			final OrderBy orderBy, final List projectedSymbols,
-			LinkedList<OrderByItem> unrelatedItems) {
-		boolean hasUnrelatedExpression = false;
-		HashSet<Expression> previousExpressions = new HashSet<Expression>();
-        for (int i = 0; i < orderBy.getVariableCount(); i++) {
-        	SingleElementSymbol querySymbol = orderBy.getVariable(i);
-        	int index = orderBy.getExpressionPosition(i);
-    		boolean isUnrelated = false;
-        	if (index == -1) {
-    			unrelatedItems.add(orderBy.getOrderByItems().get(i));
-    			isUnrelated = (querySymbol instanceof ExpressionSymbol);
-        	} else {
-        		querySymbol = (SingleElementSymbol)projectedSymbols.get(index);
-        	}
-        	Expression expr = SymbolMap.getExpression(querySymbol);
-        	if (!previousExpressions.add(expr) || (queryCommand instanceof Query && EvaluatableVisitor.willBecomeConstant(expr))) {
-                orderBy.removeOrderByItem(i--);
-        	} else if (!isUnrelated) {
-        		orderBy.getOrderByItems().get(i).setSymbol((SingleElementSymbol)querySymbol.clone());
-        	} else {
-        		hasUnrelatedExpression = true;
-        	}
-        }
-        if (orderBy.getVariableCount() == 0) {
-        	queryCommand.setOrderBy(null);
-        } 
-		return hasUnrelatedExpression;
-	}
-    
-    /**
-     * This method will alias each of the select into elements to the corresponding column name in the 
-     * target table.  This ensures that they will all be uniquely named.
-     *  
-     * @param query
-     * @throws QueryValidatorException
-     */
-    private Insert rewriteSelectInto(Query query) throws TeiidComponentException, TeiidProcessingException{
-        Into into = query.getInto();
-        try {
-            List<ElementSymbol> allIntoElements = Util.deepClone(ResolverUtil.resolveElementsInGroup(into.getGroup(), metadata), ElementSymbol.class);
-            Insert insert = new Insert(into.getGroup(), allIntoElements, Collections.emptyList());
-            query.setInto(null);
-            insert.setQueryExpression(query);
-            return correctDatatypes(insert);
-        } catch (QueryMetadataException err) {
-            throw new QueryValidatorException(err, err.getMessage());
-        } catch (TeiidComponentException err) {
-            throw new QueryValidatorException(err, err.getMessage());
-		}
-    }
-
-	private Insert correctDatatypes(Insert insert) throws TeiidComponentException, TeiidProcessingException{
-		boolean needsView = false;
-		for (int i = 0; !needsView && i < insert.getVariables().size(); i++) {
-		    SingleElementSymbol ses = (SingleElementSymbol)insert.getVariables().get(i);
-		    if (ses.getType() != insert.getQueryExpression().getProjectedSymbols().get(i).getType()) {
-		        needsView = true;
-		    }
-		}
-		if (needsView) {
-		    try {
-				insert.setQueryExpression(createInlineViewQuery(insert.getGroup(), insert.getQueryExpression(), metadata, insert.getVariables()));
-			} catch (TeiidException err) {
-	            throw new TeiidRuntimeException(err);
-	        }
-		}
-		return insert;
-	}
-
-    private void correctProjectedTypes(List actualSymbolTypes, Query query) {
-        
-        List symbols = query.getSelect().getProjectedSymbols();
-        
-        List newSymbols = SetQuery.getTypedProjectedSymbols(symbols, actualSymbolTypes, this.metadata);
-        
-        query.getSelect().setSymbols(newSymbols);
-    } 
-    
-	private SetQuery rewriteSetQuery(SetQuery setQuery)
-				 throws TeiidComponentException, TeiidProcessingException{
-        
-        if (setQuery.getProjectedTypes() != null) {
-            for (QueryCommand command : setQuery.getQueryCommands()) {
-                if (!(command instanceof Query)) {
-                    continue;
-                }
-                correctProjectedTypes(setQuery.getProjectedTypes(), (Query)command);
-            }
-            setQuery.setProjectedTypes(null, null);
-        }
-        
-        setQuery.setLeftQuery((QueryCommand)rewriteCommand(setQuery.getLeftQuery(), true));
-        setQuery.setRightQuery((QueryCommand)rewriteCommand(setQuery.getRightQuery(), true));
-
-        rewriteOrderBy(setQuery);
-        
-        if (setQuery.getLimit() != null) {
-            setQuery.setLimit(rewriteLimitClause(setQuery.getLimit()));
-        }
-        
-        return setQuery;
-    }
-
-	private FromClause rewriteFromClause(Query parent, FromClause clause)
-			 throws TeiidComponentException, TeiidProcessingException{
-		if(clause instanceof JoinPredicate) {
-			return rewriteJoinPredicate(parent, (JoinPredicate) clause);
-        } else if (clause instanceof SubqueryFromClause) {
-            rewriteSubqueryContainer((SubqueryFromClause)clause, true);
-        } else if (clause instanceof TextTable) {
-        	TextTable tt = (TextTable)clause;
-        	tt.setFile(rewriteExpressionDirect(tt.getFile()));
-        } else if (clause instanceof XMLTable) {
-        	XMLTable xt = (XMLTable)clause;
-        	xt.rewriteDefaultColumn();
-        	rewriteExpressions(clause);
-        }
-        return clause;
-	}
-
-	private JoinPredicate rewriteJoinPredicate(Query parent, JoinPredicate predicate)
-			 throws TeiidComponentException, TeiidProcessingException{
-		List joinCrits = predicate.getJoinCriteria();
-		if(joinCrits != null && joinCrits.size() > 0) {
-			//rewrite join crits by rewriting a compound criteria
-			Criteria criteria = new CompoundCriteria(new ArrayList(joinCrits));
-            joinCrits.clear();
-            criteria = rewriteCriteria(criteria);
-            if (criteria instanceof CompoundCriteria && ((CompoundCriteria)criteria).getOperator() == CompoundCriteria.AND) {
-                joinCrits.addAll(((CompoundCriteria)criteria).getCriteria());
-            } else {
-                joinCrits.add(criteria);
-            }
-			predicate.setJoinCriteria(joinCrits);
-		}
-
-        if (predicate.getJoinType() == JoinType.JOIN_UNION) {
-            predicate.setJoinType(JoinType.JOIN_FULL_OUTER);
-            predicate.setJoinCriteria(new ArrayList<Criteria>(Arrays.asList(FALSE_CRITERIA)));
-        } else if (predicate.getJoinType() == JoinType.JOIN_RIGHT_OUTER) {
-            predicate.setJoinType(JoinType.JOIN_LEFT_OUTER);
-            FromClause leftClause = predicate.getLeftClause();
-            predicate.setLeftClause(predicate.getRightClause());
-            predicate.setRightClause(leftClause);
-        }
-
-        predicate.setLeftClause( rewriteFromClause(parent, predicate.getLeftClause() ));
-        predicate.setRightClause( rewriteFromClause(parent, predicate.getRightClause() ));
-    
-		return predicate;
-	}
-    
-    /**
-     * Rewrite the criteria by evaluating some trivial cases.
-     * @param criteria The criteria to rewrite
-     * @param metadata
-     * @param userCriteria The criteria on user's command, used in rewriting HasCriteria
-     * in the procedural language.
-     * @return The re-written criteria
-     */
-    public static Criteria rewriteCriteria(Criteria criteria, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException{
-    	return new QueryRewriter(metadata, context, procCommand).rewriteCriteria(criteria);
-    }
-
-	/**
-	 * Rewrite the criteria by evaluating some trivial cases.
-	 * @param criteria The criteria to rewrite
-	 * @param userCriteria The criteria on user's command, used in rewriting HasCriteria
-	 * in the procedural language.
-	 * @return The re-written criteria
-	 */
-    private Criteria rewriteCriteria(Criteria criteria) throws TeiidComponentException, TeiidProcessingException{
-    	if(criteria instanceof CompoundCriteria) {
-            return rewriteCriteria((CompoundCriteria)criteria, true);
-		} else if(criteria instanceof NotCriteria) {
-			criteria = rewriteCriteria((NotCriteria)criteria);
-		} else if(criteria instanceof CompareCriteria) {
-            criteria = rewriteCriteria((CompareCriteria)criteria);
-        } else if(criteria instanceof SubqueryCompareCriteria) {
-            criteria = rewriteCriteria((SubqueryCompareCriteria)criteria);
-		} else if(criteria instanceof MatchCriteria) {
-            criteria = rewriteCriteria((MatchCriteria)criteria);
-		} else if(criteria instanceof SetCriteria) {
-            criteria = rewriteCriteria((SetCriteria)criteria);
-        } else if(criteria instanceof IsNullCriteria) {
-            criteria = rewriteCriteria((IsNullCriteria)criteria);
-        } else if(criteria instanceof BetweenCriteria) {
-            criteria = rewriteCriteria((BetweenCriteria)criteria);
-		} else if(criteria instanceof HasCriteria) {
-            criteria = rewriteCriteria((HasCriteria)criteria);
-		} else if(criteria instanceof TranslateCriteria) {
-            criteria = rewriteCriteria((TranslateCriteria)criteria);
-		} else if (criteria instanceof ExistsCriteria) {
-		    rewriteSubqueryContainer((SubqueryContainer)criteria, true);
-		} else if (criteria instanceof SubquerySetCriteria) {
-		    SubquerySetCriteria sub = (SubquerySetCriteria)criteria;
-		    if (isNull(sub.getExpression())) {
-		        return UNKNOWN_CRITERIA;
-		    }
-		    rewriteSubqueryContainer((SubqueryContainer)criteria, true);
-        } else if (criteria instanceof DependentSetCriteria) {
-            criteria = rewriteDependentSetCriteria((DependentSetCriteria)criteria);
-        } else if (criteria instanceof ExpressionCriteria) {
-        	return new CompareCriteria(((ExpressionCriteria) criteria).getExpression(), CompareCriteria.EQ, new Constant(Boolean.TRUE));
-        }
-    	
-        return evaluateCriteria(criteria);
-	}
-
-	private Criteria rewriteDependentSetCriteria(DependentSetCriteria dsc)
-			throws TeiidComponentException, TeiidProcessingException{
-		if (!processing) {
-			return rewriteCriteria(dsc);
-		}
-		SetCriteria setCrit = new SetCriteria();
-		setCrit.setExpression(dsc.getExpression());
-		HashSet<Object> values = new HashSet<Object>();
-		try {
-			DependentValueSource dvs = (DependentValueSource)this.context.getVariableContext().getGlobalValue(dsc.getContextSymbol());
-			ValueIterator iter = dvs.getValueIterator(dsc.getValueExpression());
-			while (iter.hasNext()) {
-				values.add(iter.next());
-			}
-		} catch (TeiidComponentException e) {
-			throw new TeiidRuntimeException(e);
-		}
-		List<Constant> constants = new ArrayList<Constant>(values.size());
-		for (Object value : values) {
-			constants.add(new Constant(value, setCrit.getExpression().getType()));
-		}
-		setCrit.setValues(constants);
-		return rewriteCriteria(setCrit);
-	}
-    
-    /**
-     * Performs simple expression flattening
-     *  
-     * @param criteria
-     * @return
-     */
-    public static Criteria optimizeCriteria(CompoundCriteria criteria, QueryMetadataInterface metadata) {
-        try {
-            return new QueryRewriter(metadata, null, null).rewriteCriteria(criteria, false);
-        } catch (TeiidException err) {
-            //shouldn't happen
-            return criteria;
-        }
-    }
-    
-    /** May be simplified if this is an AND and a sub criteria is always
-     * false or if this is an OR and a sub criteria is always true
-     */
-    private Criteria rewriteCriteria(CompoundCriteria criteria, boolean rewrite) throws TeiidComponentException, TeiidProcessingException{
-        List<Criteria> crits = criteria.getCriteria();
-        int operator = criteria.getOperator();
-
-        // Walk through crits and collect converted ones
-        LinkedHashSet<Criteria> newCrits = new LinkedHashSet<Criteria>(crits.size());
-        for (Criteria converted : crits) {
-            if (rewrite) {
-                converted = rewriteCriteria(converted);
-            } else if (converted instanceof CompoundCriteria) {
-                converted = rewriteCriteria((CompoundCriteria)converted, false);
-            }
-
-            //begin boolean optimizations
-            if(converted == TRUE_CRITERIA) {
-                if(operator == CompoundCriteria.OR) {
-                    // this OR must be true as at least one branch is always true
-                    return converted;
-                }
-            } else if(converted == FALSE_CRITERIA) {
-                if(operator == CompoundCriteria.AND) {
-                    // this AND must be false as at least one branch is always false
-                    return converted;
-                }
-            } else if (converted == UNKNOWN_CRITERIA) {
-                if (operator == CompoundCriteria.AND) {
-                    return FALSE_CRITERIA;
-                } 
-            	continue;
-            } else {
-                if (converted instanceof CompoundCriteria) {
-                    CompoundCriteria other = (CompoundCriteria)converted;
-                    if (other.getOperator() == criteria.getOperator()) {
-                        newCrits.addAll(other.getCriteria());
-                        continue;
-                    } 
-                } 
-                newCrits.add(converted);
-            }            
-		}
-
-        if(newCrits.size() == 0) {
-            if(operator == CompoundCriteria.AND) {
-                return TRUE_CRITERIA;
-            }
-            return FALSE_CRITERIA;
-        } else if(newCrits.size() == 1) {
-            // Only one sub crit now, so just return it
-            return newCrits.iterator().next();
-        } else {
-            criteria.getCriteria().clear();
-            criteria.getCriteria().addAll(newCrits);
-            return criteria;
-        }
-	}
-    
-    private Criteria evaluateCriteria(Criteria crit) throws TeiidComponentException, TeiidProcessingException{
-        if(EvaluatableVisitor.isFullyEvaluatable(crit, !processing)) {
-            try {
-            	Boolean eval = evaluator.evaluateTVL(crit, Collections.emptyList());
-                
-                if (eval == null) {
-                    return UNKNOWN_CRITERIA;
-                }
-                
-                if(Boolean.TRUE.equals(eval)) {
-                    return TRUE_CRITERIA;
-                }
-                
-                return FALSE_CRITERIA;                
-                
-            } catch(ExpressionEvaluationException e) {
-                throw new QueryValidatorException(e, "ERR.015.009.0001", QueryPlugin.Util.getString("ERR.015.009.0001", crit)); //$NON-NLS-1$ //$NON-NLS-2$
-            }
-        }
-        
-        return crit;
-    }
-
-	private Criteria rewriteCriteria(NotCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
-		Criteria innerCrit = criteria.getCriteria(); 
-        if (innerCrit instanceof CompoundCriteria) {
-        	//reduce to only negation of predicates, so that the null/unknown handling criteria is applied appropriately
-    		return rewriteCriteria(Criteria.toConjunctiveNormalForm(criteria));
-        } 
-        if (innerCrit instanceof Negatable) {
-        	((Negatable) innerCrit).negate();
-        	return rewriteCriteria(innerCrit);
-        }
-        if (innerCrit instanceof NotCriteria) {
-        	return rewriteCriteria(((NotCriteria)innerCrit).getCriteria());
-        }
-        innerCrit = rewriteCriteria(innerCrit);
-        if(innerCrit == TRUE_CRITERIA) {
-            return FALSE_CRITERIA;
-        } else if(innerCrit == FALSE_CRITERIA) {
-            return TRUE_CRITERIA;
-        } else if (innerCrit == UNKNOWN_CRITERIA) {
-            return UNKNOWN_CRITERIA;
-        }
-        criteria.setCriteria(innerCrit);
-        return criteria;
-	}
-
-    /**
-     * Rewrites "a [NOT] BETWEEN b AND c" as "a &gt;= b AND a &lt;= c", or as "a &lt;= b OR a&gt;= c"
-     * @param criteria
-     * @return
-     * @throws QueryValidatorException
-     */
-    private Criteria rewriteCriteria(BetweenCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
-        CompareCriteria lowerCriteria = new CompareCriteria(criteria.getExpression(),
-                                                            criteria.isNegated() ? CompareCriteria.LT: CompareCriteria.GE,
-                                                            criteria.getLowerExpression());
-        CompareCriteria upperCriteria = new CompareCriteria(criteria.getExpression(),
-                                                            criteria.isNegated() ? CompareCriteria.GT: CompareCriteria.LE,
-                                                            criteria.getUpperExpression());
-        CompoundCriteria newCriteria = new CompoundCriteria(criteria.isNegated() ? CompoundCriteria.OR : CompoundCriteria.AND,
-                                                            lowerCriteria,
-                                                            upperCriteria);
-
-        return rewriteCriteria(newCriteria);
-    }
-
-	private Criteria rewriteCriteria(CompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
-		Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
-		Expression rightExpr = rewriteExpressionDirect(criteria.getRightExpression());
-		criteria.setLeftExpression(leftExpr);
-		criteria.setRightExpression(rightExpr);
-
-        if (isNull(leftExpr) || isNull(rightExpr)) {
-            return UNKNOWN_CRITERIA;
-        }
-
-        boolean rightConstant = false;
-        if(EvaluatableVisitor.willBecomeConstant(rightExpr)) {
-        	rightConstant = true;
-        } else if (EvaluatableVisitor.willBecomeConstant(leftExpr)) {
-            // Swap in this particular case for connectors
-            criteria.setLeftExpression(rightExpr);
-            criteria.setRightExpression(leftExpr);
-
-            // Check for < or > operator as we have to switch it
-            switch(criteria.getOperator()) {
-                case CompareCriteria.LT:    criteria.setOperator(CompareCriteria.GT);   break;
-                case CompareCriteria.LE:    criteria.setOperator(CompareCriteria.GE);   break;
-                case CompareCriteria.GT:    criteria.setOperator(CompareCriteria.LT);   break;
-                case CompareCriteria.GE:    criteria.setOperator(CompareCriteria.LE);   break;
-            }
-            rightConstant = true;
-		} 
-        
-    	Function f = null;
-    	while (rightConstant && f != criteria.getLeftExpression() && criteria.getLeftExpression() instanceof Function) {
-            f = (Function)criteria.getLeftExpression();
-        	Criteria result = simplifyWithInverse(criteria);
-        	if (!(result instanceof CompareCriteria)) {
-        		return result;
-        	}
-        	criteria = (CompareCriteria)result;
-    	}
-        
-        Criteria modCriteria = simplifyTimestampMerge(criteria);
-        if(modCriteria instanceof CompareCriteria) {
-            modCriteria = simplifyTimestampMerge2((CompareCriteria)modCriteria);
-        }
-        return modCriteria;
-    }
-
-    public static boolean isNull(Expression expr) {
-        return expr instanceof Constant && ((Constant)expr).isNull();
-    }
-
-    /*
-     * The thing of primary importance here is that the use of the 'ANY' predicate
-     * quantifier is replaced with the canonical and equivalent 'SOME'
-     */
-    private Criteria rewriteCriteria(SubqueryCompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
-
-        Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
-        
-        if (isNull(leftExpr)) {
-            return UNKNOWN_CRITERIA;
-        }
-        
-        criteria.setLeftExpression(leftExpr);
-
-        if (criteria.getPredicateQuantifier() == SubqueryCompareCriteria.ANY){
-            criteria.setPredicateQuantifier(SubqueryCompareCriteria.SOME);
-        }
-        
-        rewriteSubqueryContainer(criteria, true);
-
-        return criteria;
-    }
-    
-    private Criteria simplifyWithInverse(CompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
-        Expression leftExpr = criteria.getLeftExpression();
-        
-        Function leftFunction = (Function) leftExpr;
-        if(isSimpleMathematicalFunction(leftFunction)) {
-            return simplifyMathematicalCriteria(criteria);
-        }   
-        if (FunctionLibrary.isConvert(leftFunction)) {
-        	return simplifyConvertFunction(criteria);
-        }
-        return simplifyParseFormatFunction(criteria);
-    }
-    
-    private boolean isSimpleMathematicalFunction(Function function) {
-        String funcName = function.getName();
-        if(funcName.equals("+") || funcName.equals("-") || funcName.equals("*") || funcName.equals("/")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            Expression[] args = function.getArgs();
-            if(args[0] instanceof Constant || args[1] instanceof Constant) {
-                return true;
-            }
-        }
-
-        // fall through - not simple mathematical
-        return false;
-    }
-
-    // Constants used in simplifying mathematical criteria
-    private Integer INTEGER_ZERO = new Integer(0);
-    private Double DOUBLE_ZERO = new Double(0);
-    private Float FLOAT_ZERO = new Float(0);
-    private Long LONG_ZERO = new Long(0);
-    private BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); //$NON-NLS-1$
-    private BigDecimal BIG_DECIMAL_ZERO = new BigDecimal("0"); //$NON-NLS-1$
-    private Short SHORT_ZERO = new Short((short)0);
-    private Byte BYTE_ZERO = new Byte((byte)0);
-
-    /**
-     * @param criteria
-     * @return CompareCriteria
-     */
-    private CompareCriteria simplifyMathematicalCriteria(CompareCriteria criteria)
-    throws TeiidComponentException, TeiidProcessingException{
-
-        Expression leftExpr = criteria.getLeftExpression();
-        Expression rightExpr = criteria.getRightExpression();
-
-        // Identify all the pieces of this criteria
-        Function function = (Function) leftExpr;
-        String funcName = function.getName();
-        Expression[] args = function.getArgs();
-        Constant const1 = null;
-        Expression expr = null;
-        if(args[1] instanceof Constant) {
-            const1 = (Constant) args[1];
-            expr = args[0];
-        } else {
-            if(funcName.equals("+") || funcName.equals("*")) { //$NON-NLS-1$ //$NON-NLS-2$
-                const1 = (Constant) args[0];
-                expr = args[1];
-            } else {
-                // If we have "5 - x = 10" or "5 / x = 10", abort!
-                return criteria;
-            }
-        }
-        int operator = criteria.getOperator();
-
-        // Determine opposite function
-        String oppFunc = null;
-        switch(funcName.charAt(0)) {
-            case '+':   oppFunc = "-";  break; //$NON-NLS-1$
-            case '-':   oppFunc = "+";  break; //$NON-NLS-1$
-            case '*':   oppFunc = "/";  break; //$NON-NLS-1$
-            case '/':   oppFunc = "*";  break; //$NON-NLS-1$
-        }
-
-        // Create a function of the two constants and evaluate it
-        Expression combinedConst = null;
-        FunctionLibrary funcLib = this.metadata.getFunctionLibrary();
-        FunctionDescriptor descriptor = funcLib.findFunction(oppFunc, new Class[] { rightExpr.getType(), const1.getType() });
-        if (descriptor == null){
-            //See defect 9380 - this can be caused by const2 being a null Constant, for example (? + 1) < null
-            return criteria;
-        }
-
-        
-        if (rightExpr instanceof Constant) {
-            Constant const2 = (Constant)rightExpr;
-            try {
-                Object result = descriptor.invokeFunction(new Object[] { const2.getValue(), const1.getValue() } );
-                combinedConst = new Constant(result, descriptor.getReturnType());
-            } catch(FunctionExecutionException e) {
-            	throw new QueryValidatorException(e, "ERR.015.009.0003", QueryPlugin.Util.getString("ERR.015.009.0003", e.getMessage())); //$NON-NLS-1$ //$NON-NLS-2$
-        	}
-        } else {
-            Function conversion = new Function(descriptor.getName(), new Expression[] { rightExpr, const1 });
-            conversion.setType(leftExpr.getType());
-            conversion.setFunctionDescriptor(descriptor);
-            combinedConst = conversion;
-            
-        }
-
-        // Flip operator if necessary
-        if(! (operator == CompareCriteria.EQ || operator == CompareCriteria.NE) &&
-             (oppFunc.equals("*") || oppFunc.equals("/")) ) { //$NON-NLS-1$ //$NON-NLS-2$
-
-            Object value = const1.getValue();
-            if(value != null) {
-                Class type = const1.getType();
-                Comparable comparisonObject = null;
-                if(type.equals(DataTypeManager.DefaultDataClasses.INTEGER)) {
-                    comparisonObject = INTEGER_ZERO;
-                } else if(type.equals(DataTypeManager.DefaultDataClasses.DOUBLE)) {
-                    comparisonObject = DOUBLE_ZERO;
-                } else if(type.equals(DataTypeManager.DefaultDataClasses.FLOAT)) {
-                    comparisonObject = FLOAT_ZERO;
-                } else if(type.equals(DataTypeManager.DefaultDataClasses.LONG)) {
-                    comparisonObject = LONG_ZERO;
-                } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_INTEGER)) {
-                    comparisonObject = BIG_INTEGER_ZERO;
-                } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_DECIMAL)) {
-                    comparisonObject = BIG_DECIMAL_ZERO;
-                } else if(type.equals(DataTypeManager.DefaultDataClasses.SHORT)) {
-                    comparisonObject = SHORT_ZERO;
-                } else if(type.equals(DataTypeManager.DefaultDataClasses.BYTE)) {
-                    comparisonObject = BYTE_ZERO;
-                } else {
-                    // Unknown type
-                    return criteria;
-                }
-
-                // If value is less than comparison object (which is zero),
-                // then need to switch operator.
-                if(comparisonObject.compareTo(value) > 0) {
-                    switch(operator) {
-                        case CompareCriteria.LE:    operator = CompareCriteria.GE;  break;
-                        case CompareCriteria.LT:    operator = CompareCriteria.GT;  break;
-                        case CompareCriteria.GE:    operator = CompareCriteria.LE;  break;
-                        case CompareCriteria.GT:    operator = CompareCriteria.LT;  break;
-                    }
-                }
-            }
-        }
-        
-        criteria.setLeftExpression(expr);
-        criteria.setRightExpression(combinedConst);
-        criteria.setOperator(operator);
-
-        // Return new simplified criteria
-        return criteria;
-    }
-
-    /**
-     * This method attempts to rewrite compare criteria of the form 
-     * 
-     * <code>convert(typedColumn, string) = '5'</code>
-     * 
-     * into 
-     * 
-     * <code>typedColumn = convert('5', typeOfColumn)</code>
-     * where 'typeOfColumn' is the type of 'typedColumn'
-     * 
-     * if, for example, the type of the column is integer, than the above
-     * can be pre-evaluated to
-     * 
-     * <code>typedColumn = 5 </code> 
-     * 
-     * Right expression has already been checked to be a Constant, left expression to be
-     * a function.  Function is known to be "convert" or "cast".
-     * 
-     * @param crit CompareCriteria
-     * @return same Criteria instance (possibly optimized)
-     * @throws QueryValidatorException
-     * @since 4.2
-     */
-    private Criteria simplifyConvertFunction(CompareCriteria crit) throws TeiidComponentException, TeiidProcessingException{
-        Function leftFunction = (Function) crit.getLeftExpression();
-        Expression leftExpr = leftFunction.getArgs()[0];
-        
-        if(!(crit.getRightExpression() instanceof Constant) 
-        		//TODO: this can be relaxed for order preserving operations
-        		|| !(crit.getOperator() == CompareCriteria.EQ || crit.getOperator() == CompareCriteria.NE)) { 
-        	return crit;
-        } 
-
-        Constant rightConstant = (Constant) crit.getRightExpression();
-        
-        String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
-
-        Constant result = ResolverUtil.convertConstant(DataTypeManager.getDataTypeName(rightConstant.getType()), leftExprTypeName, rightConstant);
-        if (result == null) {
-        	return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
-        }
-        Constant other = ResolverUtil.convertConstant(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()), result);
-        if (other == null || ((Comparable)rightConstant.getValue()).compareTo(other.getValue()) != 0) {
-        	return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
-        }
-        
-        if (!DataTypeManager.isImplicitConversion(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()))) {
-        	return crit;
-        }
-                
-    	crit.setRightExpression(result);
-        crit.setLeftExpression(leftExpr);
-
-        return crit;
-    }
-
-
-    /**
-     * This method attempts to rewrite set criteria of the form 
-     * 
-     * <code>convert(typedColumn, string) in  ('5', '6')</code>
-     * 
-     * into 
-     * 
-     * <code>typedColumn in (convert('5', typeOfColumn), convert('6', typeOfColumn)) </code>
-     * where 'typeOfColumn' is the type of 'typedColumn'
-     * 
-     * if, for example, the type of the column is integer, than the above
-     * can be pre-evaluated to
-     * 
-     * <code>typedColumn in (5,6)  </code> 
-     * 
-     * Right expression has already been checked to be a Constant, left expression to be
-     * a function.  Function is known to be "convert" or "cast".  The scope of this change
-     * will be limited to the case where the left expression is attempting to convert to
-     * 'string'.  
-     * 
-     * @param crit CompareCriteria
-     * @return same Criteria instance (possibly optimized)
-     * @throws QueryValidatorException
-     * @since 4.2
-     */
-	private Criteria simplifyConvertFunction(SetCriteria crit) throws TeiidComponentException, TeiidProcessingException{
-        Function leftFunction = (Function) crit.getExpression();
-        Expression leftExpr = leftFunction.getArgs()[0];
-        String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
-        
-        Iterator i = crit.getValues().iterator();
-        Collection newValues = new ArrayList(crit.getNumberOfValues());
-        
-        boolean convertedAll = true;
-        boolean removedSome = false;
-        while (i.hasNext()) {
-            Object next = i.next();
-            if (!(next instanceof Constant)) {
-            	convertedAll = false;
-            	continue;
-            }
-
-            Constant rightConstant = (Constant) next;
-            
-            Constant result = ResolverUtil.convertConstant(DataTypeManager.getDataTypeName(rightConstant.getType()), leftExprTypeName, rightConstant);
-            if (result != null) {
-                Constant other = ResolverUtil.convertConstant(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()), result);
-                if (other == null || ((Comparable)rightConstant.getValue()).compareTo(other.getValue()) != 0) {
-                	result = null;
-                }   
-            }
-            
-            if (result == null) {
-            	removedSome = true;
-            	i.remove();
-            } else if (DataTypeManager.isImplicitConversion(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()))) {
-            	newValues.add(result);
-            } else {
-            	convertedAll = false;
-            }
-        }
-        
-        if (!convertedAll) {
-        	if (!removedSome) {
-        		return crit; //just return as is
-        	}
-        } else {
-        	if (newValues.isEmpty()) {
-        		return getSimpliedCriteria(crit, leftExpr, !crit.isNegated(), true);
-        	}
-	        crit.setExpression(leftExpr);
-	        crit.setValues(newValues);
-        }
-        return rewriteCriteria(crit);
-    }
-        
-    private Criteria simplifyParseFormatFunction(CompareCriteria crit) throws TeiidComponentException, TeiidProcessingException{
-    	//TODO: this can be relaxed for order preserving operations
-        if(!(crit.getOperator() == CompareCriteria.EQ || crit.getOperator() == CompareCriteria.NE)) {
-        	return crit;
-        }
-    	boolean isFormat = false;
-    	Function leftFunction = (Function) crit.getLeftExpression();
-        String funcName = leftFunction.getName().toLowerCase();
-        String inverseFunction = null;
-        if(funcName.startsWith("parse")) { //$NON-NLS-1$
-            String type = funcName.substring(5);
-            inverseFunction = "format" + type; //$NON-NLS-1$
-        } else if(funcName.startsWith("format")) { //$NON-NLS-1$
-            String type = funcName.substring(6);
-            inverseFunction = "parse" + type; //$NON-NLS-1$
-            isFormat = true;
-        } else {
-            return crit;
-        }
-        Expression rightExpr = crit.getRightExpression();
-        if (!(rightExpr instanceof Constant)) {
-        	return crit;
-        }
-        Expression leftExpr = leftFunction.getArgs()[0];
-        Expression formatExpr = leftFunction.getArgs()[1];
-        if(!(formatExpr instanceof Constant)) {
-            return crit;
-        }
-        String format = (String)((Constant)formatExpr).getValue();
-        FunctionLibrary funcLib = this.metadata.getFunctionLibrary();
-        FunctionDescriptor descriptor = funcLib.findFunction(inverseFunction, new Class[] { rightExpr.getType(), formatExpr.getType() });
-        if(descriptor == null){
-            return crit;
-        }
-    	Object value = ((Constant)rightExpr).getValue();
-    	try {
-    		Object result = descriptor.invokeFunction(new Object[] {((Constant)rightExpr).getValue(), format});
-    		result = leftFunction.getFunctionDescriptor().invokeFunction(new Object[] { result, format } );
-    		if (((Comparable)value).compareTo(result) != 0) {
-    			return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
-    		}
-    	} catch(FunctionExecutionException e) {
-            //Not all numeric formats are invertable, so just return the criteria as it may still be valid
-            return crit;
-        }
-        //parseFunctions are all potentially narrowing
-        if (!isFormat) {
-        	return crit;
-        }
-        //TODO: if format is not lossy, then invert the function
-        return crit;
-    }
-      
-    /**
-     * This method applies a similar simplification as the previous method for Case 1829.  This is conceptually 
-     * the same thing but done using the timestampCreate system function.  
-     *     
-     * TIMESTAMPCREATE(rpcolli_physical.RPCOLLI.Table_B.date_field, rpcolli_physical.RPCOLLI.Table_B.time_field)
-     *    = {ts'1969-09-20 18:30:45.0'}
-     *  
-     *  -------------
-     *  
-     *   rpcolli_physical.RPCOLLI.Table_B.date_field = {d'1969-09-20'} 
-     *   AND 
-     *   rpcolli_physical.RPCOLLI.Table_B.time_field = {t'18:30:45'}
-     * 
-     * 
-     * @param criteria Compare criteria
-     * @return Simplified criteria, if possible
-     */
-    private Criteria simplifyTimestampMerge2(CompareCriteria criteria) {
-        if(criteria.getOperator() != CompareCriteria.EQ) {
-            return criteria;
-        }
-        
-        Expression leftExpr = criteria.getLeftExpression();
-        Expression rightExpr = criteria.getRightExpression();
-        
-        // Allow for concat and string literal to be on either side
-        Function tsCreateFunction = null;
-        Constant timestampConstant = null;        
-        if(leftExpr instanceof Function && rightExpr instanceof Constant) {
-            tsCreateFunction = (Function) leftExpr;
-            timestampConstant = (Constant) rightExpr;            
-        } else {
-            return criteria;
-        }
-
-        // Verify data type of constant and that constant has a value
-        if(! timestampConstant.getType().equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
-            return criteria;        
-        }
-        
-        // Verify function is timestampCreate function
-        if(! (tsCreateFunction.getName().equalsIgnoreCase("timestampCreate"))) { //$NON-NLS-1$ 
-            return criteria;
-        }
-        
-        // Get timestamp literal and break into pieces
-        Timestamp ts = (Timestamp) timestampConstant.getValue();
-        String tsStr = ts.toString();
-        Date date = Date.valueOf(tsStr.substring(0, 10)); 
-        Time time = Time.valueOf(tsStr.substring(11, 19));
-        
-        // Get timestampCreate args
-        Expression[] args = tsCreateFunction.getArgs();
-        
-        // Rebuild the function
-        CompareCriteria dateCrit = new CompareCriteria(args[0], CompareCriteria.EQ, new Constant(date, DataTypeManager.DefaultDataClasses.DATE));
-        CompareCriteria timeCrit = new CompareCriteria(args[1], CompareCriteria.EQ, new Constant(time, DataTypeManager.DefaultDataClasses.TIME));        
-        CompoundCriteria compCrit = new CompoundCriteria(CompoundCriteria.AND, dateCrit, timeCrit);
-        return compCrit;                     
-    }
-
-   /**
-    * This method also applies the same simplification for Case 1829.  This is conceptually 
-    * the same thing but done  using the timestampCreate system function.  
-    *     
-    * formatDate(rpcolli_physical.RPCOLLI.Table_B.date_field, 'yyyy-MM-dd') 
-    *    || formatTime(rpcolli_physical.RPCOLLI.Table_B.time_field, ' HH:mm:ss') = '1969-09-20 18:30:45'
-    *  
-    *  -------------
-    *  
-    *   rpcolli_physical.RPCOLLI.Table_B.date_field = {d'1969-09-20'} 
-    *   AND 
-    *   rpcolli_physical.RPCOLLI.Table_B.time_field = {t'18:30:45'}
-    * 
-    * 
-    * @param criteria Compare criteria
-    * @return Simplified criteria, if possible
-    */
-
-   private Criteria simplifyTimestampMerge(CompareCriteria criteria) {
-       if(criteria.getOperator() != CompareCriteria.EQ) {
-           return criteria;
-       }
-       
-       Expression leftExpr = criteria.getLeftExpression();
-       Expression rightExpr = criteria.getRightExpression();
-       
-       // Allow for concat and string literal to be on either side
-       Function concatFunction = null;
-       Constant timestampConstant = null;        
-       if(leftExpr instanceof Function && rightExpr instanceof Constant) {
-           concatFunction = (Function) leftExpr;
-           timestampConstant = (Constant) rightExpr;            
-       } else {
-           return criteria;
-       }
-
-       // Verify data type of string constant and that constant has a value
-       if(! timestampConstant.getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
-           return criteria;        
-       }
-       
-       // Verify function is concat function
-       if(! (concatFunction.getName().equalsIgnoreCase("concat") || concatFunction.getName().equals("||"))) { //$NON-NLS-1$ //$NON-NLS-2$
-           return criteria;
-       }
-       
-       // Verify concat has formatdate and formattime functions
-       Expression[] args = concatFunction.getArgs();
-       if(! (args[0] instanceof Function && args[1] instanceof Function)) {
-           return criteria;
-       }
-       Function formatDateFunction = (Function) args[0];
-       Function formatTimeFunction = (Function) args[1];
-       if(! (formatDateFunction.getName().equalsIgnoreCase("formatdate") && formatTimeFunction.getName().equalsIgnoreCase("formattime"))) { //$NON-NLS-1$ //$NON-NLS-2$
-           return criteria;
-       }
-       
-       // Verify format functions have constants
-       if(! (formatDateFunction.getArgs()[1] instanceof Constant && formatTimeFunction.getArgs()[1] instanceof Constant)) {
-           return criteria;
-       }
-       
-       // Verify length of combined date/time constants == timestamp constant
-       String dateFormat = (String) ((Constant)formatDateFunction.getArgs()[1]).getValue();        
-       String timeFormat = (String) ((Constant)formatTimeFunction.getArgs()[1]).getValue();        
-       String timestampValue = (String) timestampConstant.getValue();
-       
-       // Passed all the checks, so build the optimized version
-       try {
-    	   Timestamp ts = FunctionMethods.parseTimestamp(timestampValue, dateFormat + timeFormat);
-           Constant dateConstant = new Constant(TimestampWithTimezone.createDate(ts));
-           CompareCriteria dateCompare = new CompareCriteria(formatDateFunction.getArgs()[0], CompareCriteria.EQ, dateConstant);
-
-           Constant timeConstant = new Constant(TimestampWithTimezone.createTime(ts));
-           CompareCriteria timeCompare = new CompareCriteria(formatTimeFunction.getArgs()[0], CompareCriteria.EQ, timeConstant);
-           
-           CompoundCriteria compCrit = new CompoundCriteria(CompoundCriteria.AND, dateCompare, timeCompare);
-           return compCrit;
-           
-       } catch(FunctionExecutionException e) {
-           return criteria;        
-       }
-    }
-    
-    private Criteria rewriteCriteria(MatchCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
-		criteria.setLeftExpression( rewriteExpressionDirect(criteria.getLeftExpression()));
-		criteria.setRightExpression( rewriteExpressionDirect(criteria.getRightExpression()));
-        
-        if (isNull(criteria.getLeftExpression()) || isNull(criteria.getRightExpression())) {
-            return UNKNOWN_CRITERIA;
-        }
-
-        Expression rightExpr = criteria.getRightExpression();
-        if(rightExpr instanceof Constant && rightExpr.getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
-            Constant constant = (Constant) rightExpr;
-            String value = (String) constant.getValue();
-
-            char escape = criteria.getEscapeChar();
-
-            // Check whether escape char is unnecessary and remove it
-            if(escape != MatchCriteria.NULL_ESCAPE_CHAR && value.indexOf(escape) < 0) {
-                criteria.setEscapeChar(MatchCriteria.NULL_ESCAPE_CHAR);
-            }
-
-            // if the value of this string constant is '%', then we know the crit will 
-            // always be true                    
-            if ( value.equals( String.valueOf(MatchCriteria.WILDCARD_CHAR)) ) { 
-                return getSimpliedCriteria(criteria, criteria.getLeftExpression(), !criteria.isNegated(), true);                                        
-            } 
-            
-            // if both left and right expressions are strings, and the LIKE match characters ('*', '_') are not present 
-            //  in the right expression, rewrite the criteria as EQUALs rather than LIKE
-            if(DataTypeManager.DefaultDataClasses.STRING.equals(criteria.getLeftExpression().getType()) && value.indexOf(escape) < 0 && value.indexOf(MatchCriteria.MATCH_CHAR) < 0 && value.indexOf(MatchCriteria.WILDCARD_CHAR) < 0) {
-            	return rewriteCriteria(new CompareCriteria(criteria.getLeftExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, criteria.getRightExpression()));
-            }
-        }
-
-		return criteria;
-	}
-    
-	private Criteria getSimpliedCriteria(Criteria crit, Expression a, boolean outcome, boolean nullPossible) {
-		if (nullPossible) {
-			if (outcome) {
-				if (processing) {
-					return crit;
-				}
-				IsNullCriteria inc = new IsNullCriteria(a);
-				inc.setNegated(true);
-				return inc;
-			}
-		} else if (outcome) {
-			return TRUE_CRITERIA;
-		}
-		return FALSE_CRITERIA;
-	}
-	
-    private Criteria rewriteCriteria(AbstractSetCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
-        criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
-        
-        if (isNull(criteria.getExpression())) {
-            return UNKNOWN_CRITERIA;
-        }
-
-        return criteria;
-    }
-
-	private Criteria rewriteCriteria(SetCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
-		if (criteria.isAllConstants() && criteria.getValues().size() > 1) {
-			return criteria;
-		}
-		
-		criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
-        
-        if (isNull(criteria.getExpression())) {
-            return UNKNOWN_CRITERIA;
-        }
-
-		Collection vals = criteria.getValues();
-
-        LinkedHashSet newVals = new LinkedHashSet(vals.size());
-        Iterator valIter = vals.iterator();
-        boolean allConstants = true;
-        boolean hasNull = false;
-        while(valIter.hasNext()) {
-            Expression value = rewriteExpressionDirect( (Expression) valIter.next());
-            if (isNull(value)) {
-            	hasNull = true;
-            	continue;
-            }
-            allConstants &= value instanceof Constant;
-            newVals.add(value);
-        }
-        
-        int size = newVals.size();
-        if (size == 1) {
-            Expression value = (Expression)newVals.iterator().next();
-            return rewriteCriteria(new CompareCriteria(criteria.getExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, value));
-        } 
-        
-        criteria.setValues(newVals);
-        if (allConstants) {
-        	criteria.setAllConstants(true);
-        	criteria.setValues(new TreeSet(newVals));
-        }        
-        
-        if (size == 0) {
-        	if (hasNull) {
-        		return UNKNOWN_CRITERIA;
-        	}
-        	return getSimpliedCriteria(criteria, criteria.getExpression(), !criteria.isNegated(), true);
-        }
-        
-        if(criteria.getExpression() instanceof Function ) {
-            Function leftFunction = (Function)criteria.getExpression();
-            if(FunctionLibrary.isConvert(leftFunction)) {
-                return simplifyConvertFunction(criteria);        
-            }
-        }
-
-		return criteria;
-	}
-
-	private Criteria rewriteCriteria(IsNullCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
-		criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
-		return criteria;
-	}
-	
-	public static Expression rewriteExpression(Expression expression, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException{
-		return new QueryRewriter(metadata, context, procCommand).rewriteExpressionDirect(expression);
-	}
-
-    private Expression rewriteExpressionDirect(Expression expression) throws TeiidComponentException, TeiidProcessingException{
-    	if (expression instanceof Constant) {
-    		return expression;
-    	}
-    	if (expression instanceof ElementSymbol) {
-    		ElementSymbol es = (ElementSymbol)expression;
-    		Class<?> type  = es.getType();
-            if (!processing && es.isExternalReference()) {
-                String grpName = es.getGroupSymbol().getCanonicalName();
-                
-                if (variables == null) {
-                	return new Reference(es);
-                }
-                
-                Expression value = (Expression)variables.get(es.getCanonicalName());
-
-                if (value == null) {
-	                if (grpName.equals(ProcedureReservedWords.INPUTS)) {
-	                	return new Constant(null, es.getType());
-	                } 
-	                if (grpName.equals(ProcedureReservedWords.CHANGING)) {
-	                    Assertion.failed("Changing value should not be null"); //$NON-NLS-1$
-	                } 
-                } else if (value instanceof Constant) {
-                	if (value.getType() == type) {
-                		return value;
-                	}
-                	try {
-						return new Constant(FunctionMethods.convert(((Constant)value).getValue(), DataTypeManager.getDataTypeName(type)), es.getType());
-					} catch (FunctionExecutionException e) {
-						throw new QueryValidatorException(e, e.getMessage());
-					}
-                }
-                return new Reference(es);
-            }
-            return expression;
-    	}
-    	if(expression instanceof Function) {
-    		expression = rewriteFunction((Function) expression);
-		} else if (expression instanceof CaseExpression) {
-			expression = rewriteCaseExpression((CaseExpression)expression);
-        } else if (expression instanceof SearchedCaseExpression) {
-        	expression = rewriteCaseExpression((SearchedCaseExpression)expression);
-        } else if (expression instanceof ScalarSubquery) {
-        	ScalarSubquery subquery = (ScalarSubquery)expression;
-        	if (subquery.shouldEvaluate() && processing) {
-        		return new Constant(evaluator.evaluate(subquery, null), subquery.getType());
-        	}
-            rewriteSubqueryContainer(subquery, true);
-            return expression;
-        } else if (expression instanceof ExpressionSymbol) {
-        	if (expression instanceof AggregateSymbol) {
-        		expression = rewriteExpression((AggregateSymbol)expression);	
-        	} else {
-            	expression = rewriteExpressionDirect(((ExpressionSymbol)expression).getExpression());
-        	}
-        } else if (expression instanceof Criteria) {
-        	expression = rewriteCriteria((Criteria)expression);
-        } else {
-        	rewriteExpressions(expression);
-        } 
-    	
-        if(!processing) {
-        	if (!EvaluatableVisitor.isFullyEvaluatable(expression, true)) {
-        		return expression;
-        	}
-		} else if (!(expression instanceof Reference) && !EvaluatableVisitor.isEvaluatable(expression, EvaluationLevel.PROCESSING)) {
-			return expression;
-		}
-    	
-		Object value = evaluator.evaluate(expression, Collections.emptyList());
-        if (value instanceof Constant) {
-        	return (Constant)value; //multi valued substitution
-        }
-		return new Constant(value, expression.getType());
-	}
-    
-    private Expression rewriteExpression(AggregateSymbol expression) {
-    	if (expression.isBoolean()) {
-    		if (expression.getAggregateFunction() == Type.EVERY) {
-    			expression.setAggregateFunction(Type.MIN);
-    		} else {
-    			expression.setAggregateFunction(Type.MAX);
-    		}
-    	}
-    	if ((expression.getAggregateFunction() == Type.MAX || expression.getAggregateFunction() == Type.MIN)
-				&& EvaluatableVisitor.willBecomeConstant(expression.getExpression())) {
-			try {
-				return new ExpressionSymbol(expression.getName(), ResolverUtil
-						.convertExpression(expression.getExpression(),DataTypeManager.getDataTypeName(expression.getType()), metadata));
-			} catch (QueryResolverException e) {
-				//should not happen, so throw as a runtime
-				throw new TeiidRuntimeException(e);
-			}
-		}
-		return expression;
-	}
-   
-    private static Map<String, Integer> FUNCTION_MAP = new HashMap<String, Integer>();
-    
-    static {
-    	FUNCTION_MAP.put(FunctionLibrary.SPACE.toLowerCase(), 0);
-    	FUNCTION_MAP.put(FunctionLibrary.FROM_UNIXTIME.toLowerCase(), 1);
-    	FUNCTION_MAP.put(FunctionLibrary.NULLIF.toLowerCase(), 2);
-    	FUNCTION_MAP.put(FunctionLibrary.COALESCE.toLowerCase(), 3);
-    	FUNCTION_MAP.put(FunctionLibrary.CONCAT2.toLowerCase(), 4);
-    	FUNCTION_MAP.put(FunctionLibrary.TIMESTAMPADD.toLowerCase(), 5);
-    	FUNCTION_MAP.put(FunctionLibrary.PARSEDATE.toLowerCase(), 6);
-    	FUNCTION_MAP.put(FunctionLibrary.PARSETIME.toLowerCase(), 7);
-    	FUNCTION_MAP.put(FunctionLibrary.FORMATDATE.toLowerCase(), 8);
-    	FUNCTION_MAP.put(FunctionLibrary.FORMATTIME.toLowerCase(), 9);
-    }
-    
-	private Expression rewriteFunction(Function function) throws TeiidComponentException, TeiidProcessingException{
-		//rewrite alias functions
-		String functionLowerName = function.getName().toLowerCase();
-		String actualName =ALIASED_FUNCTIONS.get(functionLowerName);
-		if (actualName != null) {
-			function.setName(actualName);
-		}
-		
-		FunctionLibrary funcLibrary = this.metadata.getFunctionLibrary();
-		Integer code = FUNCTION_MAP.get(functionLowerName);
-		if (code != null) {
-			switch (code) {
-			case 0: { //space(x) => repeat(' ', x)
-				Function result = new Function(SourceSystemFunctions.REPEAT,
-						new Expression[] {new Constant(" "), function.getArg(0)}); //$NON-NLS-1$
-				//resolve the function
-				FunctionDescriptor descriptor = 
-					funcLibrary.findFunction(SourceSystemFunctions.REPEAT, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER});
-				result.setFunctionDescriptor(descriptor);
-				result.setType(DataTypeManager.DefaultDataClasses.STRING);
-				function = result;
-				break;
-			}
-			case 1: {//from_unixtime(a) => timestampadd(SQL_TSI_SECOND, a, new Timestamp(0)) 
-				Function result = new Function(FunctionLibrary.TIMESTAMPADD,
-						new Expression[] {new Constant(NonReserved.SQL_TSI_SECOND), function.getArg(0), new Constant(new Timestamp(0)) });
-				//resolve the function
-				FunctionDescriptor descriptor = 
-					funcLibrary.findFunction(FunctionLibrary.TIMESTAMPADD, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP });
-				result.setFunctionDescriptor(descriptor);
-				result.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
-				function = result;
-				break;
-			}
-			case 2: {  //rewrite nullif(a, b) => case when (a = b) then null else a
-				List when = Arrays.asList(new Criteria[] {new CompareCriteria(function.getArg(0), CompareCriteria.EQ, function.getArg(1))});
-				Constant nullConstant = new Constant(null, function.getType());
-				List then = Arrays.asList(new Expression[] {nullConstant});
-				SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
-				caseExpr.setElseExpression(function.getArg(0));
-				caseExpr.setType(function.getType());
-				return rewriteExpressionDirect(caseExpr);
-			}
-			case 3: {
-				Expression[] args = function.getArgs();
-				if (args.length == 2) {
-					Function result = new Function(SourceSystemFunctions.IFNULL,
-							new Expression[] {function.getArg(0), function.getArg(1) });
-					//resolve the function
-					FunctionDescriptor descriptor = 
-						funcLibrary.findFunction(SourceSystemFunctions.IFNULL, new Class[] { function.getType(), function.getType()  });
-					result.setFunctionDescriptor(descriptor);
-					result.setType(function.getType());
-					function = result;
-				}
-				break;
-			}
-			case 4: { //rewrite concat2 - CONCAT2(a, b) ==> CASE WHEN (a is NULL AND b is NULL) THEN NULL ELSE CONCAT( NVL(a, ''), NVL(b, '') )
-				Expression[] args = function.getArgs();
-				Function[] newArgs = new Function[args.length];
-
-				for(int i=0; i<args.length; i++) {
-					newArgs[i] = new Function(SourceSystemFunctions.IFNULL, new Expression[] {args[i], new Constant("")}); //$NON-NLS-1$
-					newArgs[i].setType(args[i].getType());
-					Assertion.assertTrue(args[i].getType() == DataTypeManager.DefaultDataClasses.STRING);
-			        FunctionDescriptor descriptor = 
-			        	funcLibrary.findFunction(SourceSystemFunctions.IFNULL, new Class[] { args[i].getType(), DataTypeManager.DefaultDataClasses.STRING });
-			        newArgs[i].setFunctionDescriptor(descriptor);
-				}
-				
-				Function concat = new Function(SourceSystemFunctions.CONCAT, newArgs);
-				concat.setType(DataTypeManager.DefaultDataClasses.STRING);
-				FunctionDescriptor descriptor = 
-					funcLibrary.findFunction(SourceSystemFunctions.CONCAT, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
-				concat.setFunctionDescriptor(descriptor);
-				
-				List when = Arrays.asList(new Criteria[] {new CompoundCriteria(CompoundCriteria.AND, new IsNullCriteria(args[0]), new IsNullCriteria(args[1]))});
-				Constant nullConstant = new Constant(null, DataTypeManager.DefaultDataClasses.STRING);
-				List then = Arrays.asList(new Expression[] {nullConstant});
-				SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
-				caseExpr.setElseExpression(concat);
-				caseExpr.setType(DataTypeManager.DefaultDataClasses.STRING);
-				return rewriteExpressionDirect(caseExpr);
-			}
-			case 5: {
-				if (function.getType() != DataTypeManager.DefaultDataClasses.TIMESTAMP) {
-					FunctionDescriptor descriptor = 
-						funcLibrary.findFunction(SourceSystemFunctions.TIMESTAMPADD, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP });
-					function.setFunctionDescriptor(descriptor);
-					Class<?> type = function.getType();
-					function.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
-					function.getArgs()[2] = ResolverUtil.getConversion(function.getArg(2), DataTypeManager.getDataTypeName(type), DataTypeManager.DefaultDataTypes.TIMESTAMP, false, funcLibrary);
-					function = ResolverUtil.getConversion(function, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.getDataTypeName(type), false, funcLibrary);
-				}
-				break;
-			}
-			case 6:
-			case 7: {
-				FunctionDescriptor descriptor = 
-					funcLibrary.findFunction(SourceSystemFunctions.PARSETIMESTAMP, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
-				function.setName(SourceSystemFunctions.PARSETIMESTAMP);
-				function.setFunctionDescriptor(descriptor);
-				Class<?> type = function.getType();
-				function.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
-				function = ResolverUtil.getConversion(function, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.getDataTypeName(type), false, funcLibrary);
-				break;
-			}
-			case 8:
-			case 9: {
-				FunctionDescriptor descriptor = 
-					funcLibrary.findFunction(SourceSystemFunctions.FORMATTIMESTAMP, new Class[] { DataTypeManager.DefaultDataClasses.TIMESTAMP, DataTypeManager.DefaultDataClasses.STRING });
-				function.setName(SourceSystemFunctions.FORMATTIMESTAMP);
-				function.setFunctionDescriptor(descriptor);
-				function.getArgs()[0] = ResolverUtil.getConversion(function.getArg(0), DataTypeManager.getDataTypeName(function.getArg(0).getType()), DataTypeManager.DefaultDataTypes.TIMESTAMP, false, funcLibrary);
-				break;
-			}
-			}
-		}
-						
-		Expression[] args = function.getArgs();
-		Expression[] newArgs = new Expression[args.length];
-		        
-        // Rewrite args
-		for(int i=0; i<args.length; i++) {
-			newArgs[i] = rewriteExpressionDirect(args[i]);
-            if (isNull(newArgs[i]) && !function.getFunctionDescriptor().isNullDependent()) {
-                return new Constant(null, function.getType());
-            }
-        }
-        function.setArgs(newArgs);
-
-        if( FunctionLibrary.isConvert(function) &&
-            newArgs[1] instanceof Constant) {
-            
-            Class srcType = newArgs[0].getType();
-            String tgtTypeName = (String) ((Constant)newArgs[1]).getValue();
-            Class tgtType = DataTypeManager.getDataTypeClass(tgtTypeName);
-
-            if(srcType != null && tgtType != null && srcType.equals(tgtType)) {
-                return newArgs[0];
-            }
-
-        }
-
-        //convert DECODESTRING function to CASE expression
-        if( function.getName().equalsIgnoreCase(FunctionLibrary.DECODESTRING) 
-                || function.getName().equalsIgnoreCase(FunctionLibrary.DECODEINTEGER)) { 
-            return convertDecodeFunction(function);
-        }
-        
-        return function;
-	}
-
-	private Expression convertDecodeFunction(Function function){
-    	Expression exprs[] = function.getArgs();
-    	String decodeString = (String)((Constant)exprs[1]).getValue();
-    	String decodeDelimiter = ","; //$NON-NLS-1$
-    	if(exprs.length == 3){
-    		decodeDelimiter = (String)((Constant)exprs[2]).getValue();
-    	}
-    	List<Criteria> newWhens = new ArrayList<Criteria>();
-    	List<Constant> newThens = new ArrayList<Constant>();
-        Constant elseConst = null;
-        StringTokenizer tokenizer = new StringTokenizer(decodeString, decodeDelimiter);
-        while (tokenizer.hasMoreTokens()) {
-            String resultString;
-            String compareString =
-            	convertString(tokenizer.nextToken().trim());
-            if (tokenizer.hasMoreTokens()) {
-                resultString = convertString(tokenizer.nextToken().trim());
-                Criteria crit;
-                if (compareString == null) {
-                	crit = new IsNullCriteria((Expression) exprs[0].clone());
-                } else {
-                	crit = new CompareCriteria((Expression) exprs[0].clone(), CompareCriteria.EQ, new Constant(compareString));
-                }
-                newWhens.add(crit);
-                newThens.add(new Constant(resultString));
-            }else {
-                elseConst = new Constant(compareString);
-            }
-        }
-        SearchedCaseExpression newCaseExpr = new SearchedCaseExpression(newWhens, newThens);
-        if(elseConst != null) {
-            newCaseExpr.setElseExpression(elseConst);
-        }else {
-            newCaseExpr.setElseExpression(exprs[0]);
-        }
-        
-        newCaseExpr.setType(function.getType());
-        return newCaseExpr;
-	}
-	
-    private static String convertString(String string) {
-        /*
-         * if there are no characters in the compare string we designate that as
-         * an indication of null.  ie if the decode string looks like this:
-         *
-         * "'this', 1,,'null'"
-         *
-         * Then if the value in the first argument is null then the String 'null' is
-         * returned from the function.
-         */
-        if (string.equals("")) { //$NON-NLS-1$
-            return null;
-        }
-
-        /*
-         * we also allow the use of the keyword null in the decode string.  if it
-         * wished to match on the string 'null' then the string must be qualified by
-         * ' designators.
-         */
-         if(string.equalsIgnoreCase("null")){ //$NON-NLS-1$
-            return null;
-         }
-
-        /*
-         * Here we check to see if the String in the decode String submitted
-         * was surrounded by String literal characters. In this case we strip
-         * these literal characters from the String.
-         */
-        if ((string.startsWith("\"") && string.endsWith("\"")) //$NON-NLS-1$ //$NON-NLS-2$
-            || (string.startsWith("'") && string.endsWith("'"))) { //$NON-NLS-1$ //$NON-NLS-2$
-            if (string.length() == 2) {
-                /*
-                 * This is an indication that the desired string to be compared is
-                 * the "" empty string, so we return it as such.
-                 */
-                string = ""; //$NON-NLS-1$
-            } else if (!string.equalsIgnoreCase("'") && !string.equalsIgnoreCase("\"")){ //$NON-NLS-1$ //$NON-NLS-2$
-                string = string.substring(1);
-                string = string.substring(0, string.length()-1);
-            }
-        }
-
-        return string;
-    }
-	
-    private Expression rewriteCaseExpression(CaseExpression expr)
-        throws TeiidComponentException, TeiidProcessingException{
-    	List<CompareCriteria> whens = new ArrayList<CompareCriteria>(expr.getWhenCount());
-    	for (Expression expression: (List<Expression>)expr.getWhen()) {
-    		whens.add(new CompareCriteria((Expression)expr.getExpression().clone(), CompareCriteria.EQ, expression));
-    	}
-    	SearchedCaseExpression sce = new SearchedCaseExpression(whens, expr.getThen());
-    	sce.setElseExpression(expr.getElseExpression());
-    	sce.setType(expr.getType());
-    	return rewriteCaseExpression(sce);
-    }
-
-    private Expression rewriteCaseExpression(SearchedCaseExpression expr)
-        throws TeiidComponentException, TeiidProcessingException{
-        int whenCount = expr.getWhenCount();
-        ArrayList<Criteria> whens = new ArrayList<Criteria>(whenCount);
-        ArrayList<Expression> thens = new ArrayList<Expression>(whenCount);
-
-        for (int i = 0; i < whenCount; i++) {
-            
-            // Check the when to see if this CASE can be rewritten due to an always true/false when
-            Criteria rewrittenWhen = rewriteCriteria(expr.getWhenCriteria(i));
-            if(rewrittenWhen == TRUE_CRITERIA) {
-                // WHEN is always true, so just return the THEN
-                return rewriteExpressionDirect(expr.getThenExpression(i));
-            }
-            if (rewrittenWhen == FALSE_CRITERIA || rewrittenWhen == UNKNOWN_CRITERIA) {
-            	continue;
-            }
-            
-            whens.add(rewrittenWhen);
-            thens.add(rewriteExpressionDirect(expr.getThenExpression(i)));
-        }
-
-        if (expr.getElseExpression() != null) {
-        	expr.setElseExpression(rewriteExpressionDirect(expr.getElseExpression()));
-        }
-        
-        Expression elseExpr = expr.getElseExpression();
-        if(whens.size() == 0) {
-            // No WHENs left, so just return the ELSE
-            if(elseExpr == null) {
-                // No else, no valid whens, just return null constant typed same as CASE
-                return new Constant(null, expr.getType());
-            } 
-
-            // Rewrite the else and return
-            return elseExpr;
-        }
-        
-        expr.setWhen(whens, thens);
-        
-        /* optimization for case 5413: 
-         *   If all of the remaining 'thens' and the 'else' evaluate to the same value, 
-         *     just return the 'else' expression.
-         */
-        
-        if ( elseExpr != null ) {
-            boolean bAllMatch = true;
-
-            for (int i = 0; i < whenCount; i++) {
-                if ( !thens.get( i ).equals(elseExpr) ) {
-                    bAllMatch = false;
-                    break;
-                }
-            }
-            
-            if ( bAllMatch ) {
-                return elseExpr;
-            }
-        }
-        
-        return expr;
-    }
-        
-    private Command rewriteExec(StoredProcedure storedProcedure) throws TeiidComponentException, TeiidProcessingException{
-        //After this method, no longer need to display named parameters
-        storedProcedure.setDisplayNamedParameters(false);
-        
-        for (SPParameter param : storedProcedure.getInputParameters()) {
-            if (!processing) {
-            	param.setExpression(rewriteExpressionDirect(param.getExpression()));
-            } else if (!(param.getExpression() instanceof Constant)) {
-            	param.setExpression(new Constant(this.evaluator.evaluate(param.getExpression(), null), param.getClassType()));
-            }
-        }
-        return storedProcedure;
-    }
-
-	private Insert rewriteInsert(Insert insert) throws TeiidComponentException, TeiidProcessingException{
-        
-        if ( insert.getQueryExpression() != null ) {
-        	insert.setQueryExpression((QueryCommand)rewriteCommand(insert.getQueryExpression(), true));
-        	return correctDatatypes(insert);
-        }
-        // Evaluate any function / constant trees in the insert values
-        List expressions = insert.getValues();
-        List evalExpressions = new ArrayList(expressions.size());
-        Iterator expIter = expressions.iterator();
-        while(expIter.hasNext()) {
-            Expression exp = (Expression) expIter.next();
-            evalExpressions.add( rewriteExpressionDirect( exp ));
-        }
-
-        insert.setValues(evalExpressions);        
-		return insert;
-	}
-
-    public static Query createInlineViewQuery(GroupSymbol group,
-                                               Command nested,
-                                               QueryMetadataInterface metadata,
-                                               List<SingleElementSymbol> actualSymbols) throws QueryMetadataException,
-                                                                  QueryResolverException,
-                                                                  TeiidComponentException {
-        Query query = new Query();
-        Select select = new Select();
-        query.setSelect(select);
-        From from = new From();
-        GroupSymbol inlineGroup = new GroupSymbol(group.getName().replace('.', '_') + "_1"); //$NON-NLS-1$
-        from.addClause(new UnaryFromClause(inlineGroup)); 
-        TempMetadataStore store = new TempMetadataStore();
-        TempMetadataAdapter tma = new TempMetadataAdapter(metadata, store);
-        if (nested instanceof QueryCommand) {
-	        Query firstProject = ((QueryCommand)nested).getProjectedQuery(); 
-	        makeSelectUnique(firstProject.getSelect(), false);
-        }
-        store.addTempGroup(inlineGroup.getName(), nested.getProjectedSymbols());
-        inlineGroup.setMetadataID(store.getTempGroupID(inlineGroup.getName()));
-        
-        List<Class<?>> actualTypes = new ArrayList<Class<?>>(nested.getProjectedSymbols().size());
-        for (SingleElementSymbol ses : actualSymbols) {
-            actualTypes.add(ses.getType());
-        }
-        List<SingleElementSymbol> selectSymbols = SetQuery.getTypedProjectedSymbols(ResolverUtil.resolveElementsInGroup(inlineGroup, tma), actualTypes, tma);
-        Iterator<SingleElementSymbol> iter = actualSymbols.iterator();
-        for (SingleElementSymbol ses : selectSymbols) {
-        	ses = (SingleElementSymbol)ses.clone();
-        	SingleElementSymbol actual = iter.next();
-        	if (!ses.getShortCanonicalName().equals(actual.getShortCanonicalName())) {
-	        	if (ses instanceof AliasSymbol) {
-	        		((AliasSymbol)ses).setName(actual.getShortName());
-	        	} else {
-	        		ses = new AliasSymbol(actual.getShortName(), ses);
-	        	}
-        	}
-			select.addSymbol(ses);
-		}
-        query.setFrom(from); 
-        QueryResolver.resolveCommand(query, tma);
-        query.setOption(nested.getOption());
-        from.getClauses().clear();
-        SubqueryFromClause sqfc = new SubqueryFromClause(inlineGroup.getName());
-        sqfc.setCommand(nested);
-        sqfc.getGroupSymbol().setMetadataID(inlineGroup.getMetadataID());
-        from.addClause(sqfc);
-        //copy the metadata onto the new query so that temp metadata adapters will be used in later calls
-        query.getTemporaryMetadata().putAll(store.getData()); 
-        return query;
-    }    
-    
-    public static void makeSelectUnique(Select select, boolean expressionSymbolsOnly) {
-        
-        select.setSymbols(select.getProjectedSymbols());
-        
-        List symbols = select.getSymbols();
-        
-        HashSet<String> uniqueNames = new HashSet<String>();
-        
-        for(int i = 0; i < symbols.size(); i++) {
-            
-            SingleElementSymbol symbol = (SingleElementSymbol)symbols.get(i);
-            
-            String baseName = symbol.getShortCanonicalName(); 
-            String name = baseName;
-
-            int exprID = 0;
-            while (true) {
-                if (uniqueNames.add(name)) {
-                    break;
-                }
-                name = baseName + '_' + (exprID++);
-            }
-            
-            if (expressionSymbolsOnly && !(symbol instanceof ExpressionSymbol)) {
-                continue;
-            }
-            
-            boolean hasAlias = false;
-            // Strip alias if it exists
-            if(symbol instanceof AliasSymbol) {
-                symbol = ((AliasSymbol)symbol).getSymbol();
-                hasAlias = true;
-            }
-            
-            if (((symbol instanceof ExpressionSymbol) && !hasAlias) || !name.equalsIgnoreCase(baseName)) {
-                symbols.set(i, new AliasSymbol(name, symbol));
-            }
-        }
-    }
-
-	private Update rewriteUpdate(Update update) throws TeiidComponentException, TeiidProcessingException{
-		if (commandType == Command.TYPE_UPDATE && variables != null) {
-	        SetClauseList newChangeList = new SetClauseList();
-	        for (SetClause entry : update.getChangeList().getClauses()) {
-	            Expression rightExpr = entry.getValue();
-	            boolean retainChange = checkInputVariables(rightExpr);
-	            if (retainChange) {
-	                newChangeList.addClause(entry.getSymbol(), entry.getValue());
-	            }
-	        }
-	        update.setChangeList(newChangeList);
-        }
-
-		// Evaluate any function on the right side of set clauses
-        for (SetClause entry : update.getChangeList().getClauses()) {
-        	entry.setValue(rewriteExpressionDirect(entry.getValue()));
-        }
-
-		// Rewrite criteria
-		Criteria crit = update.getCriteria();
-		if(crit != null) {
-			update.setCriteria(rewriteCriteria(crit));
-		}
-
-		return update;
-	}
-	
-    /**
-     * Checks variables in an expression, if the variables are INPUT variables and if
-     * none of them are changing, then this method returns a false, if all of them
-     * are changing this returns a true, if some are changing and some are not, then
-     * that is an invalid case and the method adds to the list of invalid variables.
-     * @throws TeiidComponentException, MetaMatrixProcessingException
-     */
-    private boolean checkInputVariables(Expression expr) throws TeiidComponentException, TeiidProcessingException{
-        Boolean result = null;
-        for (ElementSymbol var : ElementCollectorVisitor.getElements(expr, false)) {
-            String grpName = var.getGroupSymbol().getName();
-            if (var.isExternalReference() && grpName.equalsIgnoreCase(ProcedureReservedWords.INPUTS)) {
-                
-                String changingKey = ProcedureReservedWords.CHANGING + ElementSymbol.SEPARATOR + var.getShortCanonicalName();
-                
-                Boolean changingValue = (Boolean)((Constant)variables.get(changingKey)).getValue();
-                
-                if (result == null) {
-                    result = changingValue;
-                } else if (!result.equals(changingValue)) {
-                	throw new QueryValidatorException(QueryPlugin.Util.getString("VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state", expr)); //$NON-NLS-1$
-                }
-            }
-        }
-        
-        if (result != null) {
-            return result.booleanValue();
-        }
-        
-        return true;
-    }
-
-	private Delete rewriteDelete(Delete delete) throws TeiidComponentException, TeiidProcessingException{
-		// Rewrite criteria
-		Criteria crit = delete.getCriteria();
-		if(crit != null) {
-			delete.setCriteria(rewriteCriteria(crit));
-		}
-
-		return delete;
-	}
-    
-    private Limit rewriteLimitClause(Limit limit) throws TeiidComponentException, TeiidProcessingException{
-        if (limit.getOffset() != null) {
-            limit.setOffset(rewriteExpressionDirect(limit.getOffset()));
-        }
-        if (limit.getRowLimit() != null) {
-            limit.setRowLimit(rewriteExpressionDirect(limit.getRowLimit()));
-        }
-        return limit;
-    }
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,2515 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.rewriter;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.Assertion;
+import org.teiid.core.util.TimestampWithTimezone;
+import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.function.FunctionMethods;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.processor.relational.DependentValueSource;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.resolver.util.ResolverVisitor;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.ProcedureReservedWords;
+import org.teiid.query.sql.LanguageObject.Util;
+import org.teiid.query.sql.lang.AbstractSetCriteria;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.BetweenCriteria;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.ExpressionCriteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.GroupBy;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.Into;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.JoinPredicate;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.Limit;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.NotCriteria;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.OrderByItem;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetClause;
+import org.teiid.query.sql.lang.SetClauseList;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.TextTable;
+import org.teiid.query.sql.lang.TranslatableProcedureContainer;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.lang.WithQueryCommand;
+import org.teiid.query.sql.lang.XMLTable;
+import org.teiid.query.sql.lang.PredicateCriteria.Negatable;
+import org.teiid.query.sql.navigator.PostOrderNavigator;
+import org.teiid.query.sql.proc.Block;
+import org.teiid.query.sql.proc.CommandStatement;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+import org.teiid.query.sql.proc.CriteriaSelector;
+import org.teiid.query.sql.proc.ExpressionStatement;
+import org.teiid.query.sql.proc.HasCriteria;
+import org.teiid.query.sql.proc.IfStatement;
+import org.teiid.query.sql.proc.LoopStatement;
+import org.teiid.query.sql.proc.Statement;
+import org.teiid.query.sql.proc.TranslateCriteria;
+import org.teiid.query.sql.proc.WhileStatement;
+import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.AliasSymbol;
+import org.teiid.query.sql.symbol.CaseExpression;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.ExpressionSymbol;
+import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.ScalarSubquery;
+import org.teiid.query.sql.symbol.SearchedCaseExpression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.AggregateSymbol.Type;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.util.ValueIterator;
+import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
+import org.teiid.query.sql.visitor.CriteriaTranslatorVisitor;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.EvaluatableVisitor;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
+import org.teiid.query.sql.visitor.PredicateCollectorVisitor;
+import org.teiid.query.sql.visitor.EvaluatableVisitor.EvaluationLevel;
+import org.teiid.query.util.CommandContext;
+import org.teiid.translator.SourceSystemFunctions;
+
+
+/**
+ * Rewrites commands and command fragments to a form that is better for planning and execution.  There is a current limitation that
+ * command objects themselves cannot change type, since the same object is always used. 
+ */
+public class QueryRewriter {
+
+    public static final CompareCriteria TRUE_CRITERIA = new CompareCriteria(new Constant(new Integer(1), DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, new Constant(new Integer(1), DataTypeManager.DefaultDataClasses.INTEGER));
+    public static final CompareCriteria FALSE_CRITERIA = new CompareCriteria(new Constant(new Integer(1), DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, new Constant(new Integer(0), DataTypeManager.DefaultDataClasses.INTEGER));
+    public static final CompareCriteria UNKNOWN_CRITERIA = new CompareCriteria(new Constant(null, DataTypeManager.DefaultDataClasses.STRING), CompareCriteria.NE, new Constant(null, DataTypeManager.DefaultDataClasses.STRING));
+    
+    private static final Map<String, String> ALIASED_FUNCTIONS = new HashMap<String, String>();
+    
+    static {
+    	ALIASED_FUNCTIONS.put("lower", SourceSystemFunctions.LCASE); //$NON-NLS-1$
+    	ALIASED_FUNCTIONS.put("upper", SourceSystemFunctions.UCASE); //$NON-NLS-1$
+    	ALIASED_FUNCTIONS.put("cast", SourceSystemFunctions.CONVERT); //$NON-NLS-1$
+    	ALIASED_FUNCTIONS.put("nvl", SourceSystemFunctions.IFNULL); //$NON-NLS-1$
+    	ALIASED_FUNCTIONS.put("||", SourceSystemFunctions.CONCAT); //$NON-NLS-1$
+    	ALIASED_FUNCTIONS.put("chr", SourceSystemFunctions.CHAR); //$NON-NLS-1$
+    }
+    
+    private QueryMetadataInterface metadata;
+    private CommandContext context;
+    private CreateUpdateProcedureCommand procCommand;
+    
+    private boolean rewriteSubcommands;
+    private boolean processing;
+    private Evaluator evaluator;
+    private Map variables; //constant propagation
+    private int commandType;
+    
+    private QueryRewriter(QueryMetadataInterface metadata,
+			CommandContext context, CreateUpdateProcedureCommand procCommand) {
+		this.metadata = metadata;
+		this.context = context;
+		this.procCommand = procCommand;
+		this.evaluator = new Evaluator(Collections.emptyMap(), null, context);
+	}
+    
+    public static Command evaluateAndRewrite(Command command, Evaluator eval, CommandContext context, QueryMetadataInterface metadata) throws TeiidProcessingException, TeiidComponentException {
+    	QueryRewriter queryRewriter = new QueryRewriter(metadata, context, null);
+    	queryRewriter.evaluator = eval;
+    	queryRewriter.rewriteSubcommands = true;
+    	queryRewriter.processing = true;
+		return queryRewriter.rewriteCommand(command, false);
+    }
+
+	public static Command rewrite(Command command, CreateUpdateProcedureCommand procCommand, QueryMetadataInterface metadata, CommandContext context, Map variableValues, int commandType) throws TeiidComponentException, TeiidProcessingException{
+		QueryRewriter rewriter = new QueryRewriter(metadata, context, procCommand);
+		rewriter.rewriteSubcommands = true;
+		rewriter.variables = variableValues;
+		rewriter.commandType = commandType;
+		return rewriter.rewriteCommand(command, false);
+	}
+    
+	public static Command rewrite(Command command, QueryMetadataInterface metadata, CommandContext context) throws TeiidComponentException, TeiidProcessingException{
+		return rewrite(command, null, metadata, context, null, Command.TYPE_UNKNOWN);
+    }
+
+    /**
+     * Rewrites the command and all of its subcommands (both embedded and non-embedded)
+     *  
+     * @param command
+     * @param removeOrderBy
+     * @return
+     * @throws QueryValidatorException
+     */
+	private Command rewriteCommand(Command command, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
+		QueryMetadataInterface oldMetadata = metadata;
+		CreateUpdateProcedureCommand oldProcCommand = procCommand;
+        
+		Map tempMetadata = command.getTemporaryMetadata();
+        if(tempMetadata != null) {
+        	metadata = new TempMetadataAdapter(metadata, new TempMetadataStore(tempMetadata));
+        }
+        
+        switch(command.getType()) {
+			case Command.TYPE_QUERY:
+                QueryCommand queryCommand = (QueryCommand)command;
+            	if (removeOrderBy && queryCommand.getLimit() == null) {
+            		queryCommand.setOrderBy(null);
+                }
+            	if (queryCommand.getWith() != null) {
+            		for (WithQueryCommand withQueryCommand : queryCommand.getWith()) {
+            			if (withQueryCommand.getColumns() == null) {
+            				List<ElementSymbol> columns = ResolverUtil.resolveElementsInGroup(withQueryCommand.getGroupSymbol(), metadata);
+            				withQueryCommand.setColumns(LanguageObject.Util.deepClone(columns, ElementSymbol.class));
+            			}
+						rewriteSubqueryContainer(withQueryCommand, true);
+					}
+            	}
+                if(command instanceof Query) {
+                    command = rewriteQuery((Query) command);
+                }else {
+                    command = rewriteSetQuery((SetQuery) command);
+                }
+                break;
+            case Command.TYPE_STORED_PROCEDURE:
+                command = rewriteExec((StoredProcedure) command);
+                break;
+    		case Command.TYPE_INSERT:
+                command = rewriteInsert((Insert) command);
+                break;
+			case Command.TYPE_UPDATE:
+                command = rewriteUpdate((Update) command);
+                break;
+			case Command.TYPE_DELETE:
+                command = rewriteDelete((Delete) command);
+                break;
+            case Command.TYPE_UPDATE_PROCEDURE:
+                procCommand = (CreateUpdateProcedureCommand) command;
+                command = rewriteUpdateProcedure((CreateUpdateProcedureCommand) command);
+                break;
+            case Command.TYPE_BATCHED_UPDATE:
+            	List subCommands = ((BatchedUpdateCommand)command).getUpdateCommands();
+                for (int i = 0; i < subCommands.size(); i++) {
+                    Command subCommand = (Command)subCommands.get(i);
+                    subCommand = rewriteCommand(subCommand, false);
+                    subCommands.set(i, subCommand);
+                }
+                break;
+            	
+		}
+        
+        this.metadata = oldMetadata;
+        this.procCommand = oldProcCommand;
+        return command;
+	}
+    
+	private Command rewriteUpdateProcedure(CreateUpdateProcedureCommand command)
+								 throws TeiidComponentException, TeiidProcessingException{
+        Map oldVariables = variables;
+    	if (command.getUserCommand() != null) {
+            variables = QueryResolver.getVariableValues(command.getUserCommand(), metadata);                        
+            commandType = command.getUserCommand().getType();
+    	}
+
+		Block block = rewriteBlock(command.getBlock());
+        command.setBlock(block);
+
+        variables = oldVariables;
+        
+        return command;
+	}
+
+	private Block rewriteBlock(Block block)
+								 throws TeiidComponentException, TeiidProcessingException{
+		List statements = block.getStatements();
+        Iterator stmtIter = statements.iterator();
+
+		List newStmts = new ArrayList(statements.size());
+		// plan each statement in the block
+        while(stmtIter.hasNext()) {
+			Statement stmnt = (Statement) stmtIter.next();
+			Object newStmt = rewriteStatement(stmnt);
+			if(newStmt instanceof Statement) {
+				newStmts.add(newStmt);
+			} else if (newStmt instanceof List) {
+			    newStmts.addAll((List)newStmt);
+            }
+        }
+
+        block.setStatements(newStmts);
+
+        return block;
+	 }
+
+	private Object rewriteStatement(Statement statement)
+								 throws TeiidComponentException, TeiidProcessingException{
+
+        // evaluate the HAS Criteria on the procedure and rewrite
+		int stmtType = statement.getType();
+		switch(stmtType) {
+			case Statement.TYPE_IF:
+				IfStatement ifStmt = (IfStatement) statement;
+				Criteria ifCrit = ifStmt.getCondition();
+				Criteria evalCrit = rewriteCriteria(ifCrit);
+                
+				ifStmt.setCondition(evalCrit);
+				if(evalCrit.equals(TRUE_CRITERIA)) {
+					Block ifblock = rewriteBlock(ifStmt.getIfBlock());
+					return ifblock.getStatements();
+				} else if(evalCrit.equals(FALSE_CRITERIA) || evalCrit.equals(UNKNOWN_CRITERIA)) {
+					if(ifStmt.hasElseBlock()) {
+						Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
+						return elseBlock.getStatements();
+					} 
+                    return null;
+				} else {
+					Block ifblock = rewriteBlock(ifStmt.getIfBlock());
+					ifStmt.setIfBlock(ifblock);
+					if(ifStmt.hasElseBlock()) {
+						Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
+						ifStmt.setElseBlock(elseBlock);
+					}
+				}
+				return ifStmt;
+            case Statement.TYPE_ERROR: 
+            case Statement.TYPE_DECLARE:
+            case Statement.TYPE_ASSIGNMENT:
+				ExpressionStatement exprStmt = (ExpressionStatement) statement;
+				// replace variables to references, these references are later
+				// replaced in the processor with variable values
+				Expression expr = exprStmt.getExpression();
+				if (expr != null) {
+					expr = rewriteExpressionDirect(expr);
+	                exprStmt.setExpression(expr);
+				}
+				return exprStmt;
+            case Statement.TYPE_COMMAND:
+				CommandStatement cmdStmt = (CommandStatement) statement;
+                rewriteSubqueryContainer(cmdStmt, false);
+                
+				if(cmdStmt.getCommand().getType() == Command.TYPE_UPDATE) {
+                    Update update = (Update)cmdStmt.getCommand();
+                    if (update.getChangeList().isEmpty()) {
+                        return null;
+                    }
+				}
+                return statement;
+            case Statement.TYPE_LOOP: 
+                LoopStatement loop = (LoopStatement)statement; 
+                
+                rewriteSubqueryContainer(loop, false);
+                
+                rewriteBlock(loop.getBlock());
+                
+                if (loop.getBlock().getStatements().isEmpty()) {
+                    return null;
+                }
+                
+                return loop;
+            case Statement.TYPE_WHILE:
+                WhileStatement whileStatement = (WhileStatement) statement;
+                Criteria crit = whileStatement.getCondition();
+                crit = rewriteCriteria(crit);
+                
+                whileStatement.setCondition(crit);
+                if(crit.equals(TRUE_CRITERIA)) {
+                    throw new QueryValidatorException(QueryPlugin.Util.getString("QueryRewriter.infinite_while")); //$NON-NLS-1$
+                } else if(crit.equals(FALSE_CRITERIA) || crit.equals(UNKNOWN_CRITERIA)) {
+                    return null;
+                } 
+                whileStatement.setBlock(rewriteBlock(whileStatement.getBlock()));
+                
+                if (whileStatement.getBlock().getStatements().isEmpty()) {
+                    return null;
+                }
+                
+                return whileStatement;
+			default:
+				return statement;
+		}
+	}
+    
+    /** 
+     * @param removeOrderBy
+     * @param assStmt
+     * @throws QueryValidatorException
+     */
+    private void rewriteSubqueryContainer(SubqueryContainer container, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
+        if (rewriteSubcommands && container.getCommand() != null && container.getCommand().getProcessorPlan() == null) {
+        	container.setCommand(rewriteCommand(container.getCommand(), removeOrderBy));
+        }
+    }
+    
+	/**
+	 * <p>The HasCriteria evaluates to a TRUE_CRITERIA or a FALSE_CRITERIA, it checks to see
+	 * if type of criteria on the elements specified by the CriteriaSelector is specified on
+	 * the user's command.</p>
+	 */
+	private Criteria rewriteCriteria(HasCriteria hasCrit) {
+		Criteria userCrit = null;
+		Command userCommand = procCommand.getUserCommand();
+		int cmdType = userCommand.getType();
+		switch(cmdType) {
+			case Command.TYPE_DELETE:
+				userCrit = ((Delete)userCommand).getCriteria();
+				break;
+			case Command.TYPE_UPDATE:
+				userCrit = ((Update)userCommand).getCriteria();
+				break;
+			default:
+				return FALSE_CRITERIA;
+		}
+
+		if(userCrit == null) {
+			return FALSE_CRITERIA;
+		}
+
+		// get the CriteriaSelector, elements on the selector and the selector type
+		CriteriaSelector selector = hasCrit.getSelector();
+
+		Collection hasCritElmts = null;
+		if(selector.hasElements()) {
+			hasCritElmts = selector.getElements();
+			// collect elements present on the user's criteria and check if
+			// all of the hasCriteria elements are among them
+			Collection<ElementSymbol> userElmnts = ElementCollectorVisitor.getElements(userCrit, true);
+			if(!userElmnts.containsAll(hasCritElmts)) {
+				return FALSE_CRITERIA;
+			}
+		}
+
+		int selectorType = selector.getSelectorType();
+		// if no selector type specified return true
+		// already checked all HAS elements present on user criteria
+		if(selectorType == CriteriaSelector.NO_TYPE) {
+			return TRUE_CRITERIA;
+		}
+
+		// collect all predicate criteria present on the user's criteria
+    	Iterator criteriaIter = PredicateCollectorVisitor.getPredicates(userCrit).iterator();
+    	while(criteriaIter.hasNext()) {
+    		Criteria predicateCriteria = (Criteria) criteriaIter.next();
+    		// atleast one of the hasElemnets should be on this predicate else
+    		// proceed to the next predicate
+			Collection<ElementSymbol> predElmnts = ElementCollectorVisitor.getElements(predicateCriteria, true);
+			if(selector.hasElements()) {
+				Iterator hasIter = hasCritElmts.iterator();
+				boolean containsElmnt = false;
+				while(hasIter.hasNext()) {
+					ElementSymbol hasElmnt = (ElementSymbol) hasIter.next();
+					if(predElmnts.contains(hasElmnt)) {
+						containsElmnt = true;
+					}
+				}
+
+				if(!containsElmnt) {
+					continue;
+				}
+			}
+
+			// check if the predicate criteria type maches the type specified
+			// by the criteria selector
+    		switch(selectorType) {
+	    		case CriteriaSelector.IN:
+		    		if(predicateCriteria instanceof SetCriteria) {
+	    				return TRUE_CRITERIA;
+		    		}
+                    break;
+	    		case CriteriaSelector.LIKE:
+		    		if(predicateCriteria instanceof MatchCriteria) {
+	    				return TRUE_CRITERIA;
+		    		}
+                    break;
+                case CriteriaSelector.IS_NULL:
+                    if(predicateCriteria instanceof IsNullCriteria) {
+                        return TRUE_CRITERIA;
+                    }
+                    break;
+                case CriteriaSelector.BETWEEN:
+                    if(predicateCriteria instanceof BetweenCriteria) {
+                        return TRUE_CRITERIA;
+                    }
+                    break;
+	    		default: // EQ, GT, LT, GE, LE criteria
+		    		if(predicateCriteria instanceof CompareCriteria) {
+		    			CompareCriteria compCrit = (CompareCriteria) predicateCriteria;
+		    			if(compCrit.getOperator() == selectorType) {
+		    				return TRUE_CRITERIA;
+		    			}
+		    		}
+                    break;
+			}
+		}
+
+		return FALSE_CRITERIA;
+	}
+
+	/**
+	 * <p>TranslateCriteria is evaluated by translating elements on parts(restricted by the type
+	 * of criteria and elements specified on the CriteriaSelector) the user's criteria
+	 * using the translations provided on the TranslateCriteria and symbol mapping between
+	 * virtual group elements and the expressions on the query transformation defining the
+	 * virtual group.</p>
+	 */
+	private Criteria rewriteCriteria(TranslateCriteria transCrit)
+			 throws TeiidComponentException, TeiidProcessingException{
+
+		// criteria translated
+		Criteria translatedCriteria = null;
+
+		// get the user's command from the procedure
+		Command userCmd = procCommand.getUserCommand();
+
+		if (!(userCmd instanceof TranslatableProcedureContainer)) {
+			return FALSE_CRITERIA;
+		}
+		
+		Criteria userCriteria = ((TranslatableProcedureContainer)userCmd).getCriteria();
+		
+		if (userCriteria == null) {
+			return TRUE_CRITERIA;
+		}
+
+		// get the symbolmap between virtual elements and theie counterpart expressions
+		// from the virtual group's query transform
+		CriteriaTranslatorVisitor translateVisitor = new CriteriaTranslatorVisitor(procCommand.getSymbolMap());
+
+		translateVisitor.setCriteriaSelector(transCrit.getSelector());
+		if(transCrit.hasTranslations()) {
+			translateVisitor.setTranslations(transCrit.getTranslations());
+		}
+
+		// create a clone of user's criteria that is then translated
+		Criteria userClone = (Criteria) userCriteria.clone();
+
+		translateVisitor.translate(userClone);
+
+		// translated criteria
+		((TranslatableProcedureContainer)userCmd).addImplicitParameters(translateVisitor.getImplicitParams());
+		
+		translatedCriteria = rewriteCriteria(userClone);
+
+		// apply any implicit conversions
+		try {
+            ResolverVisitor.resolveLanguageObject(translatedCriteria, metadata);
+		} catch(TeiidException ex) {
+            throw new QueryValidatorException(ex, "ERR.015.009.0002", QueryPlugin.Util.getString("ERR.015.009.0002", translatedCriteria)); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+
+		return translatedCriteria;
+	}
+
+	private Command rewriteQuery(Query query)
+             throws TeiidComponentException, TeiidProcessingException{
+        
+        // Rewrite from clause
+        From from = query.getFrom();
+        if(from != null){
+            List clauses = new ArrayList(from.getClauses().size());
+            Iterator clauseIter = from.getClauses().iterator();
+            while(clauseIter.hasNext()) {
+                clauses.add( rewriteFromClause(query, (FromClause) clauseIter.next()) );
+            }
+            from.setClauses(clauses);
+        } else {
+            query.setOrderBy(null);
+        }
+
+        // Rewrite criteria
+        Criteria crit = query.getCriteria();
+        if(crit != null) {
+            crit = rewriteCriteria(crit);
+            if(crit == TRUE_CRITERIA) {
+                query.setCriteria(null);
+            } else {
+                query.setCriteria(crit);
+            } 
+        }
+
+        query = rewriteGroupBy(query);
+
+        // Rewrite having
+        Criteria having = query.getHaving();
+        if(having != null) {
+            query.setHaving(rewriteCriteria(having));
+        }
+                
+        rewriteExpressions(query.getSelect());
+
+        if (!query.getIsXML()) {
+            query = (Query)rewriteOrderBy(query);
+        }
+        
+        if (query.getLimit() != null) {
+            query.setLimit(rewriteLimitClause(query.getLimit()));
+        }
+        
+        if (query.getInto() != null) {
+            return rewriteSelectInto(query);
+        }
+        
+        return query;
+    }
+
+	/**
+	 * Converts a group by with expressions into a group by with only element symbols and an inline view
+	 * @param query
+	 * @return
+	 * @throws QueryValidatorException
+	 */
+	private Query rewriteGroupBy(Query query) throws TeiidComponentException, TeiidProcessingException{
+		if (query.getGroupBy() == null) {
+			return query;
+		}
+		if (isDistinctWithGroupBy(query)) {
+			query.getSelect().setDistinct(false);
+		}
+        // we check for group by expressions here to create an ANSI SQL plan
+        boolean hasExpression = false;
+        for (final Iterator iterator = query.getGroupBy().getSymbols().iterator(); !hasExpression && iterator.hasNext();) {
+            hasExpression = iterator.next() instanceof ExpressionSymbol;
+        } 
+        if (!hasExpression) {
+        	return query;
+        }
+        Select select = query.getSelect();
+        GroupBy groupBy = query.getGroupBy();
+        query.setGroupBy(null);
+        Criteria having = query.getHaving();
+        query.setHaving(null);
+        OrderBy orderBy = query.getOrderBy();
+        query.setOrderBy(null);
+        Limit limit = query.getLimit();
+        query.setLimit(null);
+        Into into = query.getInto();
+        query.setInto(null);
+        Set<Expression> newSelectColumns = new HashSet<Expression>();
+        for (final Iterator iterator = groupBy.getSymbols().iterator(); iterator.hasNext();) {
+            newSelectColumns.add(SymbolMap.getExpression((SingleElementSymbol)iterator.next()));
+        }
+        Set<AggregateSymbol> aggs = new HashSet<AggregateSymbol>();
+        aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(select, true));
+        if (having != null) {
+            aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(having, true));
+        }
+        for (AggregateSymbol aggregateSymbol : aggs) {
+            if (aggregateSymbol.getExpression() != null) {
+                Expression expr = aggregateSymbol.getExpression();
+                newSelectColumns.add(SymbolMap.getExpression(expr));
+            }
+        }
+        Select innerSelect = new Select();
+        int index = 0;
+        for (Expression expr : newSelectColumns) {
+            if (expr instanceof SingleElementSymbol) {
+                innerSelect.addSymbol((SingleElementSymbol)expr);
+            } else {
+                innerSelect.addSymbol(new ExpressionSymbol("EXPR" + index++ , expr)); //$NON-NLS-1$
+            }
+        }
+        query.setSelect(innerSelect);
+        Query outerQuery = null;
+        try {
+            outerQuery = QueryRewriter.createInlineViewQuery(new GroupSymbol("X"), query, metadata, query.getSelect().getProjectedSymbols()); //$NON-NLS-1$
+        } catch (TeiidException err) {
+            throw new TeiidRuntimeException(err);
+        }
+        Iterator iter = outerQuery.getSelect().getProjectedSymbols().iterator();
+        HashMap<Expression, SingleElementSymbol> expressionMap = new HashMap<Expression, SingleElementSymbol>();
+        for (SingleElementSymbol symbol : (List<SingleElementSymbol>)query.getSelect().getProjectedSymbols()) {
+            expressionMap.put(SymbolMap.getExpression(symbol), (SingleElementSymbol)iter.next());
+        }
+        ExpressionMappingVisitor.mapExpressions(groupBy, expressionMap);
+        outerQuery.setGroupBy(groupBy);
+        ExpressionMappingVisitor.mapExpressions(having, expressionMap);
+        outerQuery.setHaving(having);
+        ExpressionMappingVisitor.mapExpressions(orderBy, expressionMap);
+        outerQuery.setOrderBy(orderBy);
+        outerQuery.setLimit(limit);
+        ExpressionMappingVisitor.mapExpressions(select, expressionMap);
+        outerQuery.setSelect(select);
+        outerQuery.setInto(into);
+        outerQuery.setOption(query.getOption());
+        query = outerQuery;
+        rewriteExpressions(innerSelect);
+		return query;
+	}
+	
+	public static boolean isDistinctWithGroupBy(Query query) {
+		GroupBy groupBy = query.getGroupBy();
+		if (groupBy == null) {
+			return false;
+		}
+		HashSet<Expression> selectExpressions = new HashSet<Expression>();
+		for (SingleElementSymbol selectExpr : (List<SingleElementSymbol>)query.getSelect().getProjectedSymbols()) {
+			selectExpressions.add(SymbolMap.getExpression(selectExpr));
+		}
+		for (SingleElementSymbol groupByExpr :  (List<SingleElementSymbol>)groupBy.getSymbols()) {
+			if (!selectExpressions.contains(groupByExpr)) {
+				return false;
+			}
+		}
+		return true;
+	}
+    
+    private void rewriteExpressions(LanguageObject obj) throws TeiidComponentException, TeiidProcessingException{
+        if (obj == null) {
+            return;
+        }
+        ExpressionMappingVisitor visitor = new ExpressionMappingVisitor(null) {
+            /** 
+             * @see org.teiid.query.sql.visitor.ExpressionMappingVisitor#replaceExpression(org.teiid.query.sql.symbol.Expression)
+             */
+            @Override
+            public Expression replaceExpression(Expression element) {
+                try {
+                    return rewriteExpressionDirect(element);
+                } catch (TeiidException err) {
+                    throw new TeiidRuntimeException(err);
+                }
+            }
+        };
+        try {
+            PostOrderNavigator.doVisit(obj, visitor);
+        } catch (TeiidRuntimeException err) {
+            if (err.getChild() instanceof TeiidComponentException) {
+                throw (TeiidComponentException)err.getChild();
+            } 
+            if (err.getChild() instanceof TeiidProcessingException) {
+                throw (TeiidProcessingException)err.getChild();
+            } 
+            throw err;
+        }
+    }
+	
+    /**
+     * Rewrite the order by clause.
+     * Unrelated order by expressions will cause the creation of nested inline views.
+     *  
+     * @param query
+     * @throws TeiidComponentException, MetaMatrixProcessingException
+     */
+    public QueryCommand rewriteOrderBy(QueryCommand queryCommand) throws TeiidComponentException {
+    	final OrderBy orderBy = queryCommand.getOrderBy();
+        if (orderBy == null) {
+            return queryCommand;
+        }
+        Select select = queryCommand.getProjectedQuery().getSelect();
+        final List projectedSymbols = select.getProjectedSymbols();
+        
+        LinkedList<OrderByItem> unrelatedItems = new LinkedList<OrderByItem>();
+        
+        boolean hasUnrelatedExpression = rewriteOrderBy(queryCommand, orderBy,
+				projectedSymbols, unrelatedItems);
+        
+        if (orderBy.getVariableCount() == 0 || !hasUnrelatedExpression) {
+        	return queryCommand;
+        } 
+        
+        int originalSymbolCount = select.getProjectedSymbols().size();
+
+        //add unrelated to select
+        for (OrderByItem orderByItem : unrelatedItems) {
+            select.addSymbol(orderByItem.getSymbol());				
+		}
+        makeSelectUnique(select, false);
+        
+        Query query = queryCommand.getProjectedQuery();
+        
+        Into into = query.getInto();
+        query.setInto(null);
+        Limit limit = query.getLimit();
+        query.setLimit(null);
+        query.setOrderBy(null);
+        
+        Query top = null;
+        
+        try {
+        	top = createInlineViewQuery(new GroupSymbol("X"), query, metadata, select.getProjectedSymbols()); //$NON-NLS-1$
+			Iterator iter = top.getSelect().getProjectedSymbols().iterator();
+		    HashMap<Expression, SingleElementSymbol> expressionMap = new HashMap<Expression, SingleElementSymbol>();
+		    for (SingleElementSymbol symbol : (List<SingleElementSymbol>)select.getProjectedSymbols()) {
+		    	SingleElementSymbol ses = (SingleElementSymbol)iter.next();
+		        expressionMap.put(SymbolMap.getExpression(symbol), ses);
+		        expressionMap.put(new ElementSymbol(symbol.getName()), ses);
+		    }
+		    ExpressionMappingVisitor.mapExpressions(orderBy, expressionMap);
+		    //now the order by should only contain element symbols
+		} catch (TeiidException err) {
+            throw new TeiidRuntimeException(err);
+        }
+		List symbols = top.getSelect().getSymbols();
+		top.getSelect().setSymbols(symbols.subList(0, originalSymbolCount));
+		top.setInto(into);
+		top.setLimit(limit);
+		top.setOrderBy(orderBy);
+		return top;
+    }
+
+	public static boolean rewriteOrderBy(QueryCommand queryCommand,
+			final OrderBy orderBy, final List projectedSymbols,
+			LinkedList<OrderByItem> unrelatedItems) {
+		boolean hasUnrelatedExpression = false;
+		HashSet<Expression> previousExpressions = new HashSet<Expression>();
+        for (int i = 0; i < orderBy.getVariableCount(); i++) {
+        	SingleElementSymbol querySymbol = orderBy.getVariable(i);
+        	int index = orderBy.getExpressionPosition(i);
+    		boolean isUnrelated = false;
+        	if (index == -1) {
+    			unrelatedItems.add(orderBy.getOrderByItems().get(i));
+    			isUnrelated = (querySymbol instanceof ExpressionSymbol);
+        	} else {
+        		querySymbol = (SingleElementSymbol)projectedSymbols.get(index);
+        	}
+        	Expression expr = SymbolMap.getExpression(querySymbol);
+        	if (!previousExpressions.add(expr) || (queryCommand instanceof Query && EvaluatableVisitor.willBecomeConstant(expr))) {
+                orderBy.removeOrderByItem(i--);
+        	} else if (!isUnrelated) {
+        		orderBy.getOrderByItems().get(i).setSymbol((SingleElementSymbol)querySymbol.clone());
+        	} else {
+        		hasUnrelatedExpression = true;
+        	}
+        }
+        if (orderBy.getVariableCount() == 0) {
+        	queryCommand.setOrderBy(null);
+        } 
+		return hasUnrelatedExpression;
+	}
+    
+    /**
+     * This method will alias each of the select into elements to the corresponding column name in the 
+     * target table.  This ensures that they will all be uniquely named.
+     *  
+     * @param query
+     * @throws QueryValidatorException
+     */
+    private Insert rewriteSelectInto(Query query) throws TeiidComponentException, TeiidProcessingException{
+        Into into = query.getInto();
+        try {
+            List<ElementSymbol> allIntoElements = Util.deepClone(ResolverUtil.resolveElementsInGroup(into.getGroup(), metadata), ElementSymbol.class);
+            Insert insert = new Insert(into.getGroup(), allIntoElements, Collections.emptyList());
+            query.setInto(null);
+            insert.setQueryExpression(query);
+            return correctDatatypes(insert);
+        } catch (QueryMetadataException err) {
+            throw new QueryValidatorException(err, err.getMessage());
+        } catch (TeiidComponentException err) {
+            throw new QueryValidatorException(err, err.getMessage());
+		}
+    }
+
+	private Insert correctDatatypes(Insert insert) throws TeiidComponentException, TeiidProcessingException{
+		boolean needsView = false;
+		for (int i = 0; !needsView && i < insert.getVariables().size(); i++) {
+		    SingleElementSymbol ses = (SingleElementSymbol)insert.getVariables().get(i);
+		    if (ses.getType() != insert.getQueryExpression().getProjectedSymbols().get(i).getType()) {
+		        needsView = true;
+		    }
+		}
+		if (needsView) {
+		    try {
+				insert.setQueryExpression(createInlineViewQuery(insert.getGroup(), insert.getQueryExpression(), metadata, insert.getVariables()));
+			} catch (TeiidException err) {
+	            throw new TeiidRuntimeException(err);
+	        }
+		}
+		return insert;
+	}
+
+    private void correctProjectedTypes(List actualSymbolTypes, Query query) {
+        
+        List symbols = query.getSelect().getProjectedSymbols();
+        
+        List newSymbols = SetQuery.getTypedProjectedSymbols(symbols, actualSymbolTypes, this.metadata);
+        
+        query.getSelect().setSymbols(newSymbols);
+    } 
+    
+	private SetQuery rewriteSetQuery(SetQuery setQuery)
+				 throws TeiidComponentException, TeiidProcessingException{
+        
+        if (setQuery.getProjectedTypes() != null) {
+            for (QueryCommand command : setQuery.getQueryCommands()) {
+                if (!(command instanceof Query)) {
+                    continue;
+                }
+                correctProjectedTypes(setQuery.getProjectedTypes(), (Query)command);
+            }
+            setQuery.setProjectedTypes(null, null);
+        }
+        
+        setQuery.setLeftQuery((QueryCommand)rewriteCommand(setQuery.getLeftQuery(), true));
+        setQuery.setRightQuery((QueryCommand)rewriteCommand(setQuery.getRightQuery(), true));
+
+        rewriteOrderBy(setQuery);
+        
+        if (setQuery.getLimit() != null) {
+            setQuery.setLimit(rewriteLimitClause(setQuery.getLimit()));
+        }
+        
+        return setQuery;
+    }
+
+	private FromClause rewriteFromClause(Query parent, FromClause clause)
+			 throws TeiidComponentException, TeiidProcessingException{
+		if(clause instanceof JoinPredicate) {
+			return rewriteJoinPredicate(parent, (JoinPredicate) clause);
+        } else if (clause instanceof SubqueryFromClause) {
+            rewriteSubqueryContainer((SubqueryFromClause)clause, true);
+        } else if (clause instanceof TextTable) {
+        	TextTable tt = (TextTable)clause;
+        	tt.setFile(rewriteExpressionDirect(tt.getFile()));
+        } else if (clause instanceof XMLTable) {
+        	XMLTable xt = (XMLTable)clause;
+        	xt.rewriteDefaultColumn();
+        	rewriteExpressions(clause);
+        }
+        return clause;
+	}
+
+	private JoinPredicate rewriteJoinPredicate(Query parent, JoinPredicate predicate)
+			 throws TeiidComponentException, TeiidProcessingException{
+		List joinCrits = predicate.getJoinCriteria();
+		if(joinCrits != null && joinCrits.size() > 0) {
+			//rewrite join crits by rewriting a compound criteria
+			Criteria criteria = new CompoundCriteria(new ArrayList(joinCrits));
+            joinCrits.clear();
+            criteria = rewriteCriteria(criteria);
+            if (criteria instanceof CompoundCriteria && ((CompoundCriteria)criteria).getOperator() == CompoundCriteria.AND) {
+                joinCrits.addAll(((CompoundCriteria)criteria).getCriteria());
+            } else {
+                joinCrits.add(criteria);
+            }
+			predicate.setJoinCriteria(joinCrits);
+		}
+
+        if (predicate.getJoinType() == JoinType.JOIN_UNION) {
+            predicate.setJoinType(JoinType.JOIN_FULL_OUTER);
+            predicate.setJoinCriteria(new ArrayList<Criteria>(Arrays.asList(FALSE_CRITERIA)));
+        } else if (predicate.getJoinType() == JoinType.JOIN_RIGHT_OUTER) {
+            predicate.setJoinType(JoinType.JOIN_LEFT_OUTER);
+            FromClause leftClause = predicate.getLeftClause();
+            predicate.setLeftClause(predicate.getRightClause());
+            predicate.setRightClause(leftClause);
+        }
+
+        predicate.setLeftClause( rewriteFromClause(parent, predicate.getLeftClause() ));
+        predicate.setRightClause( rewriteFromClause(parent, predicate.getRightClause() ));
+    
+		return predicate;
+	}
+    
+    /**
+     * Rewrite the criteria by evaluating some trivial cases.
+     * @param criteria The criteria to rewrite
+     * @param metadata
+     * @param userCriteria The criteria on user's command, used in rewriting HasCriteria
+     * in the procedural language.
+     * @return The re-written criteria
+     */
+    public static Criteria rewriteCriteria(Criteria criteria, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException{
+    	return new QueryRewriter(metadata, context, procCommand).rewriteCriteria(criteria);
+    }
+
+	/**
+	 * Rewrite the criteria by evaluating some trivial cases.
+	 * @param criteria The criteria to rewrite
+	 * @param userCriteria The criteria on user's command, used in rewriting HasCriteria
+	 * in the procedural language.
+	 * @return The re-written criteria
+	 */
+    private Criteria rewriteCriteria(Criteria criteria) throws TeiidComponentException, TeiidProcessingException{
+    	if(criteria instanceof CompoundCriteria) {
+            return rewriteCriteria((CompoundCriteria)criteria, true);
+		} else if(criteria instanceof NotCriteria) {
+			criteria = rewriteCriteria((NotCriteria)criteria);
+		} else if(criteria instanceof CompareCriteria) {
+            criteria = rewriteCriteria((CompareCriteria)criteria);
+        } else if(criteria instanceof SubqueryCompareCriteria) {
+            criteria = rewriteCriteria((SubqueryCompareCriteria)criteria);
+		} else if(criteria instanceof MatchCriteria) {
+            criteria = rewriteCriteria((MatchCriteria)criteria);
+		} else if(criteria instanceof SetCriteria) {
+            criteria = rewriteCriteria((SetCriteria)criteria);
+        } else if(criteria instanceof IsNullCriteria) {
+            criteria = rewriteCriteria((IsNullCriteria)criteria);
+        } else if(criteria instanceof BetweenCriteria) {
+            criteria = rewriteCriteria((BetweenCriteria)criteria);
+		} else if(criteria instanceof HasCriteria) {
+            criteria = rewriteCriteria((HasCriteria)criteria);
+		} else if(criteria instanceof TranslateCriteria) {
+            criteria = rewriteCriteria((TranslateCriteria)criteria);
+		} else if (criteria instanceof ExistsCriteria) {
+		    rewriteSubqueryContainer((SubqueryContainer)criteria, true);
+		} else if (criteria instanceof SubquerySetCriteria) {
+		    SubquerySetCriteria sub = (SubquerySetCriteria)criteria;
+		    if (isNull(sub.getExpression())) {
+		        return UNKNOWN_CRITERIA;
+		    }
+		    rewriteSubqueryContainer((SubqueryContainer)criteria, true);
+        } else if (criteria instanceof DependentSetCriteria) {
+            criteria = rewriteDependentSetCriteria((DependentSetCriteria)criteria);
+        } else if (criteria instanceof ExpressionCriteria) {
+        	return new CompareCriteria(((ExpressionCriteria) criteria).getExpression(), CompareCriteria.EQ, new Constant(Boolean.TRUE));
+        }
+    	
+        return evaluateCriteria(criteria);
+	}
+
+	private Criteria rewriteDependentSetCriteria(DependentSetCriteria dsc)
+			throws TeiidComponentException, TeiidProcessingException{
+		if (!processing) {
+			return rewriteCriteria(dsc);
+		}
+		SetCriteria setCrit = new SetCriteria();
+		setCrit.setExpression(dsc.getExpression());
+		HashSet<Object> values = new HashSet<Object>();
+		try {
+			DependentValueSource dvs = (DependentValueSource)this.context.getVariableContext().getGlobalValue(dsc.getContextSymbol());
+			ValueIterator iter = dvs.getValueIterator(dsc.getValueExpression());
+			while (iter.hasNext()) {
+				values.add(iter.next());
+			}
+		} catch (TeiidComponentException e) {
+			throw new TeiidRuntimeException(e);
+		}
+		List<Constant> constants = new ArrayList<Constant>(values.size());
+		for (Object value : values) {
+			constants.add(new Constant(value, setCrit.getExpression().getType()));
+		}
+		setCrit.setValues(constants);
+		return rewriteCriteria(setCrit);
+	}
+    
+    /**
+     * Performs simple expression flattening
+     *  
+     * @param criteria
+     * @return
+     */
+    public static Criteria optimizeCriteria(CompoundCriteria criteria, QueryMetadataInterface metadata) {
+        try {
+            return new QueryRewriter(metadata, null, null).rewriteCriteria(criteria, false);
+        } catch (TeiidException err) {
+            //shouldn't happen
+            return criteria;
+        }
+    }
+    
+    /** May be simplified if this is an AND and a sub criteria is always
+     * false or if this is an OR and a sub criteria is always true
+     */
+    private Criteria rewriteCriteria(CompoundCriteria criteria, boolean rewrite) throws TeiidComponentException, TeiidProcessingException{
+        List<Criteria> crits = criteria.getCriteria();
+        int operator = criteria.getOperator();
+
+        // Walk through crits and collect converted ones
+        LinkedHashSet<Criteria> newCrits = new LinkedHashSet<Criteria>(crits.size());
+        for (Criteria converted : crits) {
+            if (rewrite) {
+                converted = rewriteCriteria(converted);
+            } else if (converted instanceof CompoundCriteria) {
+                converted = rewriteCriteria((CompoundCriteria)converted, false);
+            }
+
+            //begin boolean optimizations
+            if(converted == TRUE_CRITERIA) {
+                if(operator == CompoundCriteria.OR) {
+                    // this OR must be true as at least one branch is always true
+                    return converted;
+                }
+            } else if(converted == FALSE_CRITERIA) {
+                if(operator == CompoundCriteria.AND) {
+                    // this AND must be false as at least one branch is always false
+                    return converted;
+                }
+            } else if (converted == UNKNOWN_CRITERIA) {
+                if (operator == CompoundCriteria.AND) {
+                    return FALSE_CRITERIA;
+                } 
+            	continue;
+            } else {
+                if (converted instanceof CompoundCriteria) {
+                    CompoundCriteria other = (CompoundCriteria)converted;
+                    if (other.getOperator() == criteria.getOperator()) {
+                        newCrits.addAll(other.getCriteria());
+                        continue;
+                    } 
+                } 
+                newCrits.add(converted);
+            }            
+		}
+
+        if(newCrits.size() == 0) {
+            if(operator == CompoundCriteria.AND) {
+                return TRUE_CRITERIA;
+            }
+            return FALSE_CRITERIA;
+        } else if(newCrits.size() == 1) {
+            // Only one sub crit now, so just return it
+            return newCrits.iterator().next();
+        } else {
+            criteria.getCriteria().clear();
+            criteria.getCriteria().addAll(newCrits);
+            return criteria;
+        }
+	}
+    
+    private Criteria evaluateCriteria(Criteria crit) throws TeiidComponentException, TeiidProcessingException{
+        if(EvaluatableVisitor.isFullyEvaluatable(crit, !processing)) {
+            try {
+            	Boolean eval = evaluator.evaluateTVL(crit, Collections.emptyList());
+                
+                if (eval == null) {
+                    return UNKNOWN_CRITERIA;
+                }
+                
+                if(Boolean.TRUE.equals(eval)) {
+                    return TRUE_CRITERIA;
+                }
+                
+                return FALSE_CRITERIA;                
+                
+            } catch(ExpressionEvaluationException e) {
+                throw new QueryValidatorException(e, "ERR.015.009.0001", QueryPlugin.Util.getString("ERR.015.009.0001", crit)); //$NON-NLS-1$ //$NON-NLS-2$
+            }
+        }
+        
+        return crit;
+    }
+
+	private Criteria rewriteCriteria(NotCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+		Criteria innerCrit = criteria.getCriteria(); 
+        if (innerCrit instanceof CompoundCriteria) {
+        	//reduce to only negation of predicates, so that the null/unknown handling criteria is applied appropriately
+    		return rewriteCriteria(Criteria.toConjunctiveNormalForm(criteria));
+        } 
+        if (innerCrit instanceof Negatable) {
+        	((Negatable) innerCrit).negate();
+        	return rewriteCriteria(innerCrit);
+        }
+        if (innerCrit instanceof NotCriteria) {
+        	return rewriteCriteria(((NotCriteria)innerCrit).getCriteria());
+        }
+        innerCrit = rewriteCriteria(innerCrit);
+        if(innerCrit == TRUE_CRITERIA) {
+            return FALSE_CRITERIA;
+        } else if(innerCrit == FALSE_CRITERIA) {
+            return TRUE_CRITERIA;
+        } else if (innerCrit == UNKNOWN_CRITERIA) {
+            return UNKNOWN_CRITERIA;
+        }
+        criteria.setCriteria(innerCrit);
+        return criteria;
+	}
+
+    /**
+     * Rewrites "a [NOT] BETWEEN b AND c" as "a &gt;= b AND a &lt;= c", or as "a &lt;= b OR a&gt;= c"
+     * @param criteria
+     * @return
+     * @throws QueryValidatorException
+     */
+    private Criteria rewriteCriteria(BetweenCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+        CompareCriteria lowerCriteria = new CompareCriteria(criteria.getExpression(),
+                                                            criteria.isNegated() ? CompareCriteria.LT: CompareCriteria.GE,
+                                                            criteria.getLowerExpression());
+        CompareCriteria upperCriteria = new CompareCriteria(criteria.getExpression(),
+                                                            criteria.isNegated() ? CompareCriteria.GT: CompareCriteria.LE,
+                                                            criteria.getUpperExpression());
+        CompoundCriteria newCriteria = new CompoundCriteria(criteria.isNegated() ? CompoundCriteria.OR : CompoundCriteria.AND,
+                                                            lowerCriteria,
+                                                            upperCriteria);
+
+        return rewriteCriteria(newCriteria);
+    }
+
+	private Criteria rewriteCriteria(CompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+		Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
+		Expression rightExpr = rewriteExpressionDirect(criteria.getRightExpression());
+		criteria.setLeftExpression(leftExpr);
+		criteria.setRightExpression(rightExpr);
+
+        if (isNull(leftExpr) || isNull(rightExpr)) {
+            return UNKNOWN_CRITERIA;
+        }
+
+        boolean rightConstant = false;
+        if(EvaluatableVisitor.willBecomeConstant(rightExpr)) {
+        	rightConstant = true;
+        } else if (EvaluatableVisitor.willBecomeConstant(leftExpr)) {
+            // Swap in this particular case for connectors
+            criteria.setLeftExpression(rightExpr);
+            criteria.setRightExpression(leftExpr);
+
+            // Check for < or > operator as we have to switch it
+            switch(criteria.getOperator()) {
+                case CompareCriteria.LT:    criteria.setOperator(CompareCriteria.GT);   break;
+                case CompareCriteria.LE:    criteria.setOperator(CompareCriteria.GE);   break;
+                case CompareCriteria.GT:    criteria.setOperator(CompareCriteria.LT);   break;
+                case CompareCriteria.GE:    criteria.setOperator(CompareCriteria.LE);   break;
+            }
+            rightConstant = true;
+		} 
+        
+    	Function f = null;
+    	while (rightConstant && f != criteria.getLeftExpression() && criteria.getLeftExpression() instanceof Function) {
+            f = (Function)criteria.getLeftExpression();
+        	Criteria result = simplifyWithInverse(criteria);
+        	if (!(result instanceof CompareCriteria)) {
+        		return result;
+        	}
+        	criteria = (CompareCriteria)result;
+    	}
+        
+        Criteria modCriteria = simplifyTimestampMerge(criteria);
+        if(modCriteria instanceof CompareCriteria) {
+            modCriteria = simplifyTimestampMerge2((CompareCriteria)modCriteria);
+        }
+        return modCriteria;
+    }
+
+    public static boolean isNull(Expression expr) {
+        return expr instanceof Constant && ((Constant)expr).isNull();
+    }
+
+    /*
+     * The thing of primary importance here is that the use of the 'ANY' predicate
+     * quantifier is replaced with the canonical and equivalent 'SOME'
+     */
+    private Criteria rewriteCriteria(SubqueryCompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+
+        Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
+        
+        if (isNull(leftExpr)) {
+            return UNKNOWN_CRITERIA;
+        }
+        
+        criteria.setLeftExpression(leftExpr);
+
+        if (criteria.getPredicateQuantifier() == SubqueryCompareCriteria.ANY){
+            criteria.setPredicateQuantifier(SubqueryCompareCriteria.SOME);
+        }
+        
+        rewriteSubqueryContainer(criteria, true);
+
+        return criteria;
+    }
+    
+    private Criteria simplifyWithInverse(CompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+        Expression leftExpr = criteria.getLeftExpression();
+        
+        Function leftFunction = (Function) leftExpr;
+        if(isSimpleMathematicalFunction(leftFunction)) {
+            return simplifyMathematicalCriteria(criteria);
+        }   
+        if (FunctionLibrary.isConvert(leftFunction)) {
+        	return simplifyConvertFunction(criteria);
+        }
+        return simplifyParseFormatFunction(criteria);
+    }
+    
+    private boolean isSimpleMathematicalFunction(Function function) {
+        String funcName = function.getName();
+        if(funcName.equals("+") || funcName.equals("-") || funcName.equals("*") || funcName.equals("/")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            Expression[] args = function.getArgs();
+            if(args[0] instanceof Constant || args[1] instanceof Constant) {
+                return true;
+            }
+        }
+
+        // fall through - not simple mathematical
+        return false;
+    }
+
+    // Constants used in simplifying mathematical criteria
+    private Integer INTEGER_ZERO = new Integer(0);
+    private Double DOUBLE_ZERO = new Double(0);
+    private Float FLOAT_ZERO = new Float(0);
+    private Long LONG_ZERO = new Long(0);
+    private BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); //$NON-NLS-1$
+    private BigDecimal BIG_DECIMAL_ZERO = new BigDecimal("0"); //$NON-NLS-1$
+    private Short SHORT_ZERO = new Short((short)0);
+    private Byte BYTE_ZERO = new Byte((byte)0);
+
+    /**
+     * @param criteria
+     * @return CompareCriteria
+     */
+    private CompareCriteria simplifyMathematicalCriteria(CompareCriteria criteria)
+    throws TeiidComponentException, TeiidProcessingException{
+
+        Expression leftExpr = criteria.getLeftExpression();
+        Expression rightExpr = criteria.getRightExpression();
+
+        // Identify all the pieces of this criteria
+        Function function = (Function) leftExpr;
+        String funcName = function.getName();
+        Expression[] args = function.getArgs();
+        Constant const1 = null;
+        Expression expr = null;
+        if(args[1] instanceof Constant) {
+            const1 = (Constant) args[1];
+            expr = args[0];
+        } else {
+            if(funcName.equals("+") || funcName.equals("*")) { //$NON-NLS-1$ //$NON-NLS-2$
+                const1 = (Constant) args[0];
+                expr = args[1];
+            } else {
+                // If we have "5 - x = 10" or "5 / x = 10", abort!
+                return criteria;
+            }
+        }
+        int operator = criteria.getOperator();
+
+        // Determine opposite function
+        String oppFunc = null;
+        switch(funcName.charAt(0)) {
+            case '+':   oppFunc = "-";  break; //$NON-NLS-1$
+            case '-':   oppFunc = "+";  break; //$NON-NLS-1$
+            case '*':   oppFunc = "/";  break; //$NON-NLS-1$
+            case '/':   oppFunc = "*";  break; //$NON-NLS-1$
+        }
+
+        // Create a function of the two constants and evaluate it
+        Expression combinedConst = null;
+        FunctionLibrary funcLib = this.metadata.getFunctionLibrary();
+        FunctionDescriptor descriptor = funcLib.findFunction(oppFunc, new Class[] { rightExpr.getType(), const1.getType() });
+        if (descriptor == null){
+            //See defect 9380 - this can be caused by const2 being a null Constant, for example (? + 1) < null
+            return criteria;
+        }
+
+        
+        if (rightExpr instanceof Constant) {
+            Constant const2 = (Constant)rightExpr;
+            try {
+                Object result = descriptor.invokeFunction(new Object[] { const2.getValue(), const1.getValue() } );
+                combinedConst = new Constant(result, descriptor.getReturnType());
+            } catch(FunctionExecutionException e) {
+            	throw new QueryValidatorException(e, "ERR.015.009.0003", QueryPlugin.Util.getString("ERR.015.009.0003", e.getMessage())); //$NON-NLS-1$ //$NON-NLS-2$
+        	}
+        } else {
+            Function conversion = new Function(descriptor.getName(), new Expression[] { rightExpr, const1 });
+            conversion.setType(leftExpr.getType());
+            conversion.setFunctionDescriptor(descriptor);
+            combinedConst = conversion;
+            
+        }
+
+        // Flip operator if necessary
+        if(! (operator == CompareCriteria.EQ || operator == CompareCriteria.NE) &&
+             (oppFunc.equals("*") || oppFunc.equals("/")) ) { //$NON-NLS-1$ //$NON-NLS-2$
+
+            Object value = const1.getValue();
+            if(value != null) {
+                Class type = const1.getType();
+                Comparable comparisonObject = null;
+                if(type.equals(DataTypeManager.DefaultDataClasses.INTEGER)) {
+                    comparisonObject = INTEGER_ZERO;
+                } else if(type.equals(DataTypeManager.DefaultDataClasses.DOUBLE)) {
+                    comparisonObject = DOUBLE_ZERO;
+                } else if(type.equals(DataTypeManager.DefaultDataClasses.FLOAT)) {
+                    comparisonObject = FLOAT_ZERO;
+                } else if(type.equals(DataTypeManager.DefaultDataClasses.LONG)) {
+                    comparisonObject = LONG_ZERO;
+                } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_INTEGER)) {
+                    comparisonObject = BIG_INTEGER_ZERO;
+                } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_DECIMAL)) {
+                    comparisonObject = BIG_DECIMAL_ZERO;
+                } else if(type.equals(DataTypeManager.DefaultDataClasses.SHORT)) {
+                    comparisonObject = SHORT_ZERO;
+                } else if(type.equals(DataTypeManager.DefaultDataClasses.BYTE)) {
+                    comparisonObject = BYTE_ZERO;
+                } else {
+                    // Unknown type
+                    return criteria;
+                }
+
+                // If value is less than comparison object (which is zero),
+                // then need to switch operator.
+                if(comparisonObject.compareTo(value) > 0) {
+                    switch(operator) {
+                        case CompareCriteria.LE:    operator = CompareCriteria.GE;  break;
+                        case CompareCriteria.LT:    operator = CompareCriteria.GT;  break;
+                        case CompareCriteria.GE:    operator = CompareCriteria.LE;  break;
+                        case CompareCriteria.GT:    operator = CompareCriteria.LT;  break;
+                    }
+                }
+            }
+        }
+        
+        criteria.setLeftExpression(expr);
+        criteria.setRightExpression(combinedConst);
+        criteria.setOperator(operator);
+
+        // Return new simplified criteria
+        return criteria;
+    }
+
+    /**
+     * This method attempts to rewrite compare criteria of the form 
+     * 
+     * <code>convert(typedColumn, string) = '5'</code>
+     * 
+     * into 
+     * 
+     * <code>typedColumn = convert('5', typeOfColumn)</code>
+     * where 'typeOfColumn' is the type of 'typedColumn'
+     * 
+     * if, for example, the type of the column is integer, than the above
+     * can be pre-evaluated to
+     * 
+     * <code>typedColumn = 5 </code> 
+     * 
+     * Right expression has already been checked to be a Constant, left expression to be
+     * a function.  Function is known to be "convert" or "cast".
+     * 
+     * @param crit CompareCriteria
+     * @return same Criteria instance (possibly optimized)
+     * @throws QueryValidatorException
+     * @since 4.2
+     */
+    private Criteria simplifyConvertFunction(CompareCriteria crit) throws TeiidComponentException, TeiidProcessingException{
+        Function leftFunction = (Function) crit.getLeftExpression();
+        Expression leftExpr = leftFunction.getArgs()[0];
+        
+        if(!(crit.getRightExpression() instanceof Constant) 
+        		//TODO: this can be relaxed for order preserving operations
+        		|| !(crit.getOperator() == CompareCriteria.EQ || crit.getOperator() == CompareCriteria.NE)) { 
+        	return crit;
+        } 
+
+        Constant rightConstant = (Constant) crit.getRightExpression();
+        
+        String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
+
+        Constant result = ResolverUtil.convertConstant(DataTypeManager.getDataTypeName(rightConstant.getType()), leftExprTypeName, rightConstant);
+        if (result == null) {
+        	return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
+        }
+        Constant other = ResolverUtil.convertConstant(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()), result);
+        if (other == null || ((Comparable)rightConstant.getValue()).compareTo(other.getValue()) != 0) {
+        	return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
+        }
+        
+        if (!DataTypeManager.isImplicitConversion(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()))) {
+        	return crit;
+        }
+                
+    	crit.setRightExpression(result);
+        crit.setLeftExpression(leftExpr);
+
+        return crit;
+    }
+
+
+    /**
+     * This method attempts to rewrite set criteria of the form 
+     * 
+     * <code>convert(typedColumn, string) in  ('5', '6')</code>
+     * 
+     * into 
+     * 
+     * <code>typedColumn in (convert('5', typeOfColumn), convert('6', typeOfColumn)) </code>
+     * where 'typeOfColumn' is the type of 'typedColumn'
+     * 
+     * if, for example, the type of the column is integer, than the above
+     * can be pre-evaluated to
+     * 
+     * <code>typedColumn in (5,6)  </code> 
+     * 
+     * Right expression has already been checked to be a Constant, left expression to be
+     * a function.  Function is known to be "convert" or "cast".  The scope of this change
+     * will be limited to the case where the left expression is attempting to convert to
+     * 'string'.  
+     * 
+     * @param crit CompareCriteria
+     * @return same Criteria instance (possibly optimized)
+     * @throws QueryValidatorException
+     * @since 4.2
+     */
+	private Criteria simplifyConvertFunction(SetCriteria crit) throws TeiidComponentException, TeiidProcessingException{
+        Function leftFunction = (Function) crit.getExpression();
+        Expression leftExpr = leftFunction.getArgs()[0];
+        String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
+        
+        Iterator i = crit.getValues().iterator();
+        Collection newValues = new ArrayList(crit.getNumberOfValues());
+        
+        boolean convertedAll = true;
+        boolean removedSome = false;
+        while (i.hasNext()) {
+            Object next = i.next();
+            if (!(next instanceof Constant)) {
+            	convertedAll = false;
+            	continue;
+            }
+
+            Constant rightConstant = (Constant) next;
+            
+            Constant result = ResolverUtil.convertConstant(DataTypeManager.getDataTypeName(rightConstant.getType()), leftExprTypeName, rightConstant);
+            if (result != null) {
+                Constant other = ResolverUtil.convertConstant(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()), result);
+                if (other == null || ((Comparable)rightConstant.getValue()).compareTo(other.getValue()) != 0) {
+                	result = null;
+                }   
+            }
+            
+            if (result == null) {
+            	removedSome = true;
+            	i.remove();
+            } else if (DataTypeManager.isImplicitConversion(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()))) {
+            	newValues.add(result);
+            } else {
+            	convertedAll = false;
+            }
+        }
+        
+        if (!convertedAll) {
+        	if (!removedSome) {
+        		return crit; //just return as is
+        	}
+        } else {
+        	if (newValues.isEmpty()) {
+        		return getSimpliedCriteria(crit, leftExpr, !crit.isNegated(), true);
+        	}
+	        crit.setExpression(leftExpr);
+	        crit.setValues(newValues);
+        }
+        return rewriteCriteria(crit);
+    }
+        
+    private Criteria simplifyParseFormatFunction(CompareCriteria crit) throws TeiidComponentException, TeiidProcessingException{
+    	//TODO: this can be relaxed for order preserving operations
+        if(!(crit.getOperator() == CompareCriteria.EQ || crit.getOperator() == CompareCriteria.NE)) {
+        	return crit;
+        }
+    	boolean isFormat = false;
+    	Function leftFunction = (Function) crit.getLeftExpression();
+        String funcName = leftFunction.getName().toLowerCase();
+        String inverseFunction = null;
+        if(funcName.startsWith("parse")) { //$NON-NLS-1$
+            String type = funcName.substring(5);
+            inverseFunction = "format" + type; //$NON-NLS-1$
+        } else if(funcName.startsWith("format")) { //$NON-NLS-1$
+            String type = funcName.substring(6);
+            inverseFunction = "parse" + type; //$NON-NLS-1$
+            isFormat = true;
+        } else {
+            return crit;
+        }
+        Expression rightExpr = crit.getRightExpression();
+        if (!(rightExpr instanceof Constant)) {
+        	return crit;
+        }
+        Expression leftExpr = leftFunction.getArgs()[0];
+        Expression formatExpr = leftFunction.getArgs()[1];
+        if(!(formatExpr instanceof Constant)) {
+            return crit;
+        }
+        String format = (String)((Constant)formatExpr).getValue();
+        FunctionLibrary funcLib = this.metadata.getFunctionLibrary();
+        FunctionDescriptor descriptor = funcLib.findFunction(inverseFunction, new Class[] { rightExpr.getType(), formatExpr.getType() });
+        if(descriptor == null){
+            return crit;
+        }
+    	Object value = ((Constant)rightExpr).getValue();
+    	try {
+    		Object result = descriptor.invokeFunction(new Object[] {((Constant)rightExpr).getValue(), format});
+    		result = leftFunction.getFunctionDescriptor().invokeFunction(new Object[] { result, format } );
+    		if (((Comparable)value).compareTo(result) != 0) {
+    			return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
+    		}
+    	} catch(FunctionExecutionException e) {
+            //Not all numeric formats are invertable, so just return the criteria as it may still be valid
+            return crit;
+        }
+        //parseFunctions are all potentially narrowing
+        if (!isFormat) {
+        	return crit;
+        }
+        //TODO: if format is not lossy, then invert the function
+        return crit;
+    }
+      
+    /**
+     * This method applies a similar simplification as the previous method for Case 1829.  This is conceptually 
+     * the same thing but done using the timestampCreate system function.  
+     *     
+     * TIMESTAMPCREATE(rpcolli_physical.RPCOLLI.Table_B.date_field, rpcolli_physical.RPCOLLI.Table_B.time_field)
+     *    = {ts'1969-09-20 18:30:45.0'}
+     *  
+     *  -------------
+     *  
+     *   rpcolli_physical.RPCOLLI.Table_B.date_field = {d'1969-09-20'} 
+     *   AND 
+     *   rpcolli_physical.RPCOLLI.Table_B.time_field = {t'18:30:45'}
+     * 
+     * 
+     * @param criteria Compare criteria
+     * @return Simplified criteria, if possible
+     */
+    private Criteria simplifyTimestampMerge2(CompareCriteria criteria) {
+        if(criteria.getOperator() != CompareCriteria.EQ) {
+            return criteria;
+        }
+        
+        Expression leftExpr = criteria.getLeftExpression();
+        Expression rightExpr = criteria.getRightExpression();
+        
+        // Allow for concat and string literal to be on either side
+        Function tsCreateFunction = null;
+        Constant timestampConstant = null;        
+        if(leftExpr instanceof Function && rightExpr instanceof Constant) {
+            tsCreateFunction = (Function) leftExpr;
+            timestampConstant = (Constant) rightExpr;            
+        } else {
+            return criteria;
+        }
+
+        // Verify data type of constant and that constant has a value
+        if(! timestampConstant.getType().equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
+            return criteria;        
+        }
+        
+        // Verify function is timestampCreate function
+        if(! (tsCreateFunction.getName().equalsIgnoreCase("timestampCreate"))) { //$NON-NLS-1$ 
+            return criteria;
+        }
+        
+        // Get timestamp literal and break into pieces
+        Timestamp ts = (Timestamp) timestampConstant.getValue();
+        String tsStr = ts.toString();
+        Date date = Date.valueOf(tsStr.substring(0, 10)); 
+        Time time = Time.valueOf(tsStr.substring(11, 19));
+        
+        // Get timestampCreate args
+        Expression[] args = tsCreateFunction.getArgs();
+        
+        // Rebuild the function
+        CompareCriteria dateCrit = new CompareCriteria(args[0], CompareCriteria.EQ, new Constant(date, DataTypeManager.DefaultDataClasses.DATE));
+        CompareCriteria timeCrit = new CompareCriteria(args[1], CompareCriteria.EQ, new Constant(time, DataTypeManager.DefaultDataClasses.TIME));        
+        CompoundCriteria compCrit = new CompoundCriteria(CompoundCriteria.AND, dateCrit, timeCrit);
+        return compCrit;                     
+    }
+
+   /**
+    * This method also applies the same simplification for Case 1829.  This is conceptually 
+    * the same thing but done  using the timestampCreate system function.  
+    *     
+    * formatDate(rpcolli_physical.RPCOLLI.Table_B.date_field, 'yyyy-MM-dd') 
+    *    || formatTime(rpcolli_physical.RPCOLLI.Table_B.time_field, ' HH:mm:ss') = '1969-09-20 18:30:45'
+    *  
+    *  -------------
+    *  
+    *   rpcolli_physical.RPCOLLI.Table_B.date_field = {d'1969-09-20'} 
+    *   AND 
+    *   rpcolli_physical.RPCOLLI.Table_B.time_field = {t'18:30:45'}
+    * 
+    * 
+    * @param criteria Compare criteria
+    * @return Simplified criteria, if possible
+    */
+
+   private Criteria simplifyTimestampMerge(CompareCriteria criteria) {
+       if(criteria.getOperator() != CompareCriteria.EQ) {
+           return criteria;
+       }
+       
+       Expression leftExpr = criteria.getLeftExpression();
+       Expression rightExpr = criteria.getRightExpression();
+       
+       // Allow for concat and string literal to be on either side
+       Function concatFunction = null;
+       Constant timestampConstant = null;        
+       if(leftExpr instanceof Function && rightExpr instanceof Constant) {
+           concatFunction = (Function) leftExpr;
+           timestampConstant = (Constant) rightExpr;            
+       } else {
+           return criteria;
+       }
+
+       // Verify data type of string constant and that constant has a value
+       if(! timestampConstant.getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
+           return criteria;        
+       }
+       
+       // Verify function is concat function
+       if(! (concatFunction.getName().equalsIgnoreCase("concat") || concatFunction.getName().equals("||"))) { //$NON-NLS-1$ //$NON-NLS-2$
+           return criteria;
+       }
+       
+       // Verify concat has formatdate and formattime functions
+       Expression[] args = concatFunction.getArgs();
+       if(! (args[0] instanceof Function && args[1] instanceof Function)) {
+           return criteria;
+       }
+       Function formatDateFunction = (Function) args[0];
+       Function formatTimeFunction = (Function) args[1];
+       if(! (formatDateFunction.getName().equalsIgnoreCase("formatdate") && formatTimeFunction.getName().equalsIgnoreCase("formattime"))) { //$NON-NLS-1$ //$NON-NLS-2$
+           return criteria;
+       }
+       
+       // Verify format functions have constants
+       if(! (formatDateFunction.getArgs()[1] instanceof Constant && formatTimeFunction.getArgs()[1] instanceof Constant)) {
+           return criteria;
+       }
+       
+       // Verify length of combined date/time constants == timestamp constant
+       String dateFormat = (String) ((Constant)formatDateFunction.getArgs()[1]).getValue();        
+       String timeFormat = (String) ((Constant)formatTimeFunction.getArgs()[1]).getValue();        
+       String timestampValue = (String) timestampConstant.getValue();
+       
+       // Passed all the checks, so build the optimized version
+       try {
+    	   Timestamp ts = FunctionMethods.parseTimestamp(timestampValue, dateFormat + timeFormat);
+           Constant dateConstant = new Constant(TimestampWithTimezone.createDate(ts));
+           CompareCriteria dateCompare = new CompareCriteria(formatDateFunction.getArgs()[0], CompareCriteria.EQ, dateConstant);
+
+           Constant timeConstant = new Constant(TimestampWithTimezone.createTime(ts));
+           CompareCriteria timeCompare = new CompareCriteria(formatTimeFunction.getArgs()[0], CompareCriteria.EQ, timeConstant);
+           
+           CompoundCriteria compCrit = new CompoundCriteria(CompoundCriteria.AND, dateCompare, timeCompare);
+           return compCrit;
+           
+       } catch(FunctionExecutionException e) {
+           return criteria;        
+       }
+    }
+    
+    private Criteria rewriteCriteria(MatchCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+		criteria.setLeftExpression( rewriteExpressionDirect(criteria.getLeftExpression()));
+		criteria.setRightExpression( rewriteExpressionDirect(criteria.getRightExpression()));
+        
+        if (isNull(criteria.getLeftExpression()) || isNull(criteria.getRightExpression())) {
+            return UNKNOWN_CRITERIA;
+        }
+
+        Expression rightExpr = criteria.getRightExpression();
+        if(rightExpr instanceof Constant && rightExpr.getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
+            Constant constant = (Constant) rightExpr;
+            String value = (String) constant.getValue();
+
+            char escape = criteria.getEscapeChar();
+
+            // Check whether escape char is unnecessary and remove it
+            if(escape != MatchCriteria.NULL_ESCAPE_CHAR && value.indexOf(escape) < 0) {
+                criteria.setEscapeChar(MatchCriteria.NULL_ESCAPE_CHAR);
+            }
+
+            // if the value of this string constant is '%', then we know the crit will 
+            // always be true                    
+            if ( value.equals( String.valueOf(MatchCriteria.WILDCARD_CHAR)) ) { 
+                return getSimpliedCriteria(criteria, criteria.getLeftExpression(), !criteria.isNegated(), true);                                        
+            } 
+            
+            // if both left and right expressions are strings, and the LIKE match characters ('*', '_') are not present 
+            //  in the right expression, rewrite the criteria as EQUALs rather than LIKE
+            if(DataTypeManager.DefaultDataClasses.STRING.equals(criteria.getLeftExpression().getType()) && value.indexOf(escape) < 0 && value.indexOf(MatchCriteria.MATCH_CHAR) < 0 && value.indexOf(MatchCriteria.WILDCARD_CHAR) < 0) {
+            	return rewriteCriteria(new CompareCriteria(criteria.getLeftExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, criteria.getRightExpression()));
+            }
+        }
+
+		return criteria;
+	}
+    
+	private Criteria getSimpliedCriteria(Criteria crit, Expression a, boolean outcome, boolean nullPossible) {
+		if (nullPossible) {
+			if (outcome) {
+				if (processing) {
+					return crit;
+				}
+				IsNullCriteria inc = new IsNullCriteria(a);
+				inc.setNegated(true);
+				return inc;
+			}
+		} else if (outcome) {
+			return TRUE_CRITERIA;
+		}
+		return FALSE_CRITERIA;
+	}
+	
+    private Criteria rewriteCriteria(AbstractSetCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+        criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
+        
+        if (isNull(criteria.getExpression())) {
+            return UNKNOWN_CRITERIA;
+        }
+
+        return criteria;
+    }
+
+	private Criteria rewriteCriteria(SetCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+		if (criteria.isAllConstants() && criteria.getValues().size() > 1) {
+			return criteria;
+		}
+		
+		criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
+        
+        if (isNull(criteria.getExpression())) {
+            return UNKNOWN_CRITERIA;
+        }
+
+		Collection vals = criteria.getValues();
+
+        LinkedHashSet newVals = new LinkedHashSet(vals.size());
+        Iterator valIter = vals.iterator();
+        boolean allConstants = true;
+        boolean hasNull = false;
+        while(valIter.hasNext()) {
+            Expression value = rewriteExpressionDirect( (Expression) valIter.next());
+            if (isNull(value)) {
+            	hasNull = true;
+            	continue;
+            }
+            allConstants &= value instanceof Constant;
+            newVals.add(value);
+        }
+        
+        int size = newVals.size();
+        if (size == 1) {
+            Expression value = (Expression)newVals.iterator().next();
+            return rewriteCriteria(new CompareCriteria(criteria.getExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, value));
+        } 
+        
+        criteria.setValues(newVals);
+        if (allConstants) {
+        	criteria.setAllConstants(true);
+        	criteria.setValues(new TreeSet(newVals));
+        }        
+        
+        if (size == 0) {
+        	if (hasNull) {
+        		return UNKNOWN_CRITERIA;
+        	}
+        	return getSimpliedCriteria(criteria, criteria.getExpression(), !criteria.isNegated(), true);
+        }
+        
+        if(criteria.getExpression() instanceof Function ) {
+            Function leftFunction = (Function)criteria.getExpression();
+            if(FunctionLibrary.isConvert(leftFunction)) {
+                return simplifyConvertFunction(criteria);        
+            }
+        }
+
+		return criteria;
+	}
+
+	private Criteria rewriteCriteria(IsNullCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+		criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
+		return criteria;
+	}
+	
+	public static Expression rewriteExpression(Expression expression, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException{
+		return new QueryRewriter(metadata, context, procCommand).rewriteExpressionDirect(expression);
+	}
+
+    private Expression rewriteExpressionDirect(Expression expression) throws TeiidComponentException, TeiidProcessingException{
+    	if (expression instanceof Constant) {
+    		return expression;
+    	}
+    	if (expression instanceof ElementSymbol) {
+    		ElementSymbol es = (ElementSymbol)expression;
+    		Class<?> type  = es.getType();
+            if (!processing && es.isExternalReference()) {
+                String grpName = es.getGroupSymbol().getCanonicalName();
+                
+                if (variables == null) {
+                	return new Reference(es);
+                }
+                
+                Expression value = (Expression)variables.get(es.getCanonicalName());
+
+                if (value == null) {
+	                if (grpName.equals(ProcedureReservedWords.INPUTS)) {
+	                	return new Constant(null, es.getType());
+	                } 
+	                if (grpName.equals(ProcedureReservedWords.CHANGING)) {
+	                    Assertion.failed("Changing value should not be null"); //$NON-NLS-1$
+	                } 
+                } else if (value instanceof Constant) {
+                	if (value.getType() == type) {
+                		return value;
+                	}
+                	try {
+						return new Constant(FunctionMethods.convert(((Constant)value).getValue(), DataTypeManager.getDataTypeName(type)), es.getType());
+					} catch (FunctionExecutionException e) {
+						throw new QueryValidatorException(e, e.getMessage());
+					}
+                }
+                return new Reference(es);
+            }
+            return expression;
+    	}
+    	if(expression instanceof Function) {
+    		expression = rewriteFunction((Function) expression);
+		} else if (expression instanceof CaseExpression) {
+			expression = rewriteCaseExpression((CaseExpression)expression);
+        } else if (expression instanceof SearchedCaseExpression) {
+        	expression = rewriteCaseExpression((SearchedCaseExpression)expression);
+        } else if (expression instanceof ScalarSubquery) {
+        	ScalarSubquery subquery = (ScalarSubquery)expression;
+        	if (subquery.shouldEvaluate() && processing) {
+        		return new Constant(evaluator.evaluate(subquery, null), subquery.getType());
+        	}
+            rewriteSubqueryContainer(subquery, true);
+            return expression;
+        } else if (expression instanceof ExpressionSymbol) {
+        	if (expression instanceof AggregateSymbol) {
+        		expression = rewriteExpression((AggregateSymbol)expression);	
+        	} else {
+            	expression = rewriteExpressionDirect(((ExpressionSymbol)expression).getExpression());
+        	}
+        } else if (expression instanceof Criteria) {
+        	expression = rewriteCriteria((Criteria)expression);
+        } else {
+        	rewriteExpressions(expression);
+        } 
+    	
+        if(!processing) {
+        	if (!EvaluatableVisitor.isFullyEvaluatable(expression, true)) {
+        		return expression;
+        	}
+		} else if (!(expression instanceof Reference) && !EvaluatableVisitor.isEvaluatable(expression, EvaluationLevel.PROCESSING)) {
+			return expression;
+		}
+    	
+		Object value = evaluator.evaluate(expression, Collections.emptyList());
+        if (value instanceof Constant) {
+        	return (Constant)value; //multi valued substitution
+        }
+		return new Constant(value, expression.getType());
+	}
+    
+    private Expression rewriteExpression(AggregateSymbol expression) {
+    	if (expression.isBoolean()) {
+    		if (expression.getAggregateFunction() == Type.EVERY) {
+    			expression.setAggregateFunction(Type.MIN);
+    		} else {
+    			expression.setAggregateFunction(Type.MAX);
+    		}
+    	}
+    	if ((expression.getAggregateFunction() == Type.MAX || expression.getAggregateFunction() == Type.MIN)
+				&& EvaluatableVisitor.willBecomeConstant(expression.getExpression())) {
+			try {
+				return new ExpressionSymbol(expression.getName(), ResolverUtil
+						.convertExpression(expression.getExpression(),DataTypeManager.getDataTypeName(expression.getType()), metadata));
+			} catch (QueryResolverException e) {
+				//should not happen, so throw as a runtime
+				throw new TeiidRuntimeException(e);
+			}
+		}
+		return expression;
+	}
+   
+    private static Map<String, Integer> FUNCTION_MAP = new HashMap<String, Integer>();
+    
+    static {
+    	FUNCTION_MAP.put(FunctionLibrary.SPACE.toLowerCase(), 0);
+    	FUNCTION_MAP.put(FunctionLibrary.FROM_UNIXTIME.toLowerCase(), 1);
+    	FUNCTION_MAP.put(FunctionLibrary.NULLIF.toLowerCase(), 2);
+    	FUNCTION_MAP.put(FunctionLibrary.COALESCE.toLowerCase(), 3);
+    	FUNCTION_MAP.put(FunctionLibrary.CONCAT2.toLowerCase(), 4);
+    	FUNCTION_MAP.put(FunctionLibrary.TIMESTAMPADD.toLowerCase(), 5);
+    	FUNCTION_MAP.put(FunctionLibrary.PARSEDATE.toLowerCase(), 6);
+    	FUNCTION_MAP.put(FunctionLibrary.PARSETIME.toLowerCase(), 7);
+    	FUNCTION_MAP.put(FunctionLibrary.FORMATDATE.toLowerCase(), 8);
+    	FUNCTION_MAP.put(FunctionLibrary.FORMATTIME.toLowerCase(), 9);
+    }
+    
+	private Expression rewriteFunction(Function function) throws TeiidComponentException, TeiidProcessingException{
+		//rewrite alias functions
+		String functionLowerName = function.getName().toLowerCase();
+		String actualName =ALIASED_FUNCTIONS.get(functionLowerName);
+		if (actualName != null) {
+			function.setName(actualName);
+		}
+		
+		FunctionLibrary funcLibrary = this.metadata.getFunctionLibrary();
+		Integer code = FUNCTION_MAP.get(functionLowerName);
+		if (code != null) {
+			switch (code) {
+			case 0: { //space(x) => repeat(' ', x)
+				Function result = new Function(SourceSystemFunctions.REPEAT,
+						new Expression[] {new Constant(" "), function.getArg(0)}); //$NON-NLS-1$
+				//resolve the function
+				FunctionDescriptor descriptor = 
+					funcLibrary.findFunction(SourceSystemFunctions.REPEAT, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER});
+				result.setFunctionDescriptor(descriptor);
+				result.setType(DataTypeManager.DefaultDataClasses.STRING);
+				function = result;
+				break;
+			}
+			case 1: {//from_unixtime(a) => timestampadd(SQL_TSI_SECOND, a, new Timestamp(0)) 
+				Function result = new Function(FunctionLibrary.TIMESTAMPADD,
+						new Expression[] {new Constant(NonReserved.SQL_TSI_SECOND), function.getArg(0), new Constant(new Timestamp(0)) });
+				//resolve the function
+				FunctionDescriptor descriptor = 
+					funcLibrary.findFunction(FunctionLibrary.TIMESTAMPADD, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP });
+				result.setFunctionDescriptor(descriptor);
+				result.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
+				function = result;
+				break;
+			}
+			case 2: {  //rewrite nullif(a, b) => case when (a = b) then null else a
+				List when = Arrays.asList(new Criteria[] {new CompareCriteria(function.getArg(0), CompareCriteria.EQ, function.getArg(1))});
+				Constant nullConstant = new Constant(null, function.getType());
+				List then = Arrays.asList(new Expression[] {nullConstant});
+				SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
+				caseExpr.setElseExpression(function.getArg(0));
+				caseExpr.setType(function.getType());
+				return rewriteExpressionDirect(caseExpr);
+			}
+			case 3: {
+				Expression[] args = function.getArgs();
+				if (args.length == 2) {
+					Function result = new Function(SourceSystemFunctions.IFNULL,
+							new Expression[] {function.getArg(0), function.getArg(1) });
+					//resolve the function
+					FunctionDescriptor descriptor = 
+						funcLibrary.findFunction(SourceSystemFunctions.IFNULL, new Class[] { function.getType(), function.getType()  });
+					result.setFunctionDescriptor(descriptor);
+					result.setType(function.getType());
+					function = result;
+				}
+				break;
+			}
+			case 4: { //rewrite concat2 - CONCAT2(a, b) ==> CASE WHEN (a is NULL AND b is NULL) THEN NULL ELSE CONCAT( NVL(a, ''), NVL(b, '') )
+				Expression[] args = function.getArgs();
+				Function[] newArgs = new Function[args.length];
+
+				for(int i=0; i<args.length; i++) {
+					newArgs[i] = new Function(SourceSystemFunctions.IFNULL, new Expression[] {args[i], new Constant("")}); //$NON-NLS-1$
+					newArgs[i].setType(args[i].getType());
+					Assertion.assertTrue(args[i].getType() == DataTypeManager.DefaultDataClasses.STRING);
+			        FunctionDescriptor descriptor = 
+			        	funcLibrary.findFunction(SourceSystemFunctions.IFNULL, new Class[] { args[i].getType(), DataTypeManager.DefaultDataClasses.STRING });
+			        newArgs[i].setFunctionDescriptor(descriptor);
+				}
+				
+				Function concat = new Function(SourceSystemFunctions.CONCAT, newArgs);
+				concat.setType(DataTypeManager.DefaultDataClasses.STRING);
+				FunctionDescriptor descriptor = 
+					funcLibrary.findFunction(SourceSystemFunctions.CONCAT, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
+				concat.setFunctionDescriptor(descriptor);
+				
+				List when = Arrays.asList(new Criteria[] {new CompoundCriteria(CompoundCriteria.AND, new IsNullCriteria(args[0]), new IsNullCriteria(args[1]))});
+				Constant nullConstant = new Constant(null, DataTypeManager.DefaultDataClasses.STRING);
+				List then = Arrays.asList(new Expression[] {nullConstant});
+				SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
+				caseExpr.setElseExpression(concat);
+				caseExpr.setType(DataTypeManager.DefaultDataClasses.STRING);
+				return rewriteExpressionDirect(caseExpr);
+			}
+			case 5: {
+				if (function.getType() != DataTypeManager.DefaultDataClasses.TIMESTAMP) {
+					FunctionDescriptor descriptor = 
+						funcLibrary.findFunction(SourceSystemFunctions.TIMESTAMPADD, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP });
+					function.setFunctionDescriptor(descriptor);
+					Class<?> type = function.getType();
+					function.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
+					function.getArgs()[2] = ResolverUtil.getConversion(function.getArg(2), DataTypeManager.getDataTypeName(type), DataTypeManager.DefaultDataTypes.TIMESTAMP, false, funcLibrary);
+					function = ResolverUtil.getConversion(function, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.getDataTypeName(type), false, funcLibrary);
+				}
+				break;
+			}
+			case 6:
+			case 7: {
+				FunctionDescriptor descriptor = 
+					funcLibrary.findFunction(SourceSystemFunctions.PARSETIMESTAMP, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
+				function.setName(SourceSystemFunctions.PARSETIMESTAMP);
+				function.setFunctionDescriptor(descriptor);
+				Class<?> type = function.getType();
+				function.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
+				function = ResolverUtil.getConversion(function, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.getDataTypeName(type), false, funcLibrary);
+				break;
+			}
+			case 8:
+			case 9: {
+				FunctionDescriptor descriptor = 
+					funcLibrary.findFunction(SourceSystemFunctions.FORMATTIMESTAMP, new Class[] { DataTypeManager.DefaultDataClasses.TIMESTAMP, DataTypeManager.DefaultDataClasses.STRING });
+				function.setName(SourceSystemFunctions.FORMATTIMESTAMP);
+				function.setFunctionDescriptor(descriptor);
+				function.getArgs()[0] = ResolverUtil.getConversion(function.getArg(0), DataTypeManager.getDataTypeName(function.getArg(0).getType()), DataTypeManager.DefaultDataTypes.TIMESTAMP, false, funcLibrary);
+				break;
+			}
+			}
+		}
+						
+		Expression[] args = function.getArgs();
+		Expression[] newArgs = new Expression[args.length];
+		        
+        // Rewrite args
+		for(int i=0; i<args.length; i++) {
+			newArgs[i] = rewriteExpressionDirect(args[i]);
+            if (isNull(newArgs[i]) && !function.getFunctionDescriptor().isNullDependent()) {
+                return new Constant(null, function.getType());
+            }
+        }
+        function.setArgs(newArgs);
+
+        if( FunctionLibrary.isConvert(function) &&
+            newArgs[1] instanceof Constant) {
+            
+            Class srcType = newArgs[0].getType();
+            String tgtTypeName = (String) ((Constant)newArgs[1]).getValue();
+            Class tgtType = DataTypeManager.getDataTypeClass(tgtTypeName);
+
+            if(srcType != null && tgtType != null && srcType.equals(tgtType)) {
+                return newArgs[0];
+            }
+
+        }
+
+        //convert DECODESTRING function to CASE expression
+        if( function.getName().equalsIgnoreCase(FunctionLibrary.DECODESTRING) 
+                || function.getName().equalsIgnoreCase(FunctionLibrary.DECODEINTEGER)) { 
+            return convertDecodeFunction(function);
+        }
+        
+        return function;
+	}
+
+	private Expression convertDecodeFunction(Function function){
+    	Expression exprs[] = function.getArgs();
+    	String decodeString = (String)((Constant)exprs[1]).getValue();
+    	String decodeDelimiter = ","; //$NON-NLS-1$
+    	if(exprs.length == 3){
+    		decodeDelimiter = (String)((Constant)exprs[2]).getValue();
+    	}
+    	List<Criteria> newWhens = new ArrayList<Criteria>();
+    	List<Constant> newThens = new ArrayList<Constant>();
+        Constant elseConst = null;
+        StringTokenizer tokenizer = new StringTokenizer(decodeString, decodeDelimiter);
+        while (tokenizer.hasMoreTokens()) {
+            String resultString;
+            String compareString =
+            	convertString(tokenizer.nextToken().trim());
+            if (tokenizer.hasMoreTokens()) {
+                resultString = convertString(tokenizer.nextToken().trim());
+                Criteria crit;
+                if (compareString == null) {
+                	crit = new IsNullCriteria((Expression) exprs[0].clone());
+                } else {
+                	crit = new CompareCriteria((Expression) exprs[0].clone(), CompareCriteria.EQ, new Constant(compareString));
+                }
+                newWhens.add(crit);
+                newThens.add(new Constant(resultString));
+            }else {
+                elseConst = new Constant(compareString);
+            }
+        }
+        SearchedCaseExpression newCaseExpr = new SearchedCaseExpression(newWhens, newThens);
+        if(elseConst != null) {
+            newCaseExpr.setElseExpression(elseConst);
+        }else {
+            newCaseExpr.setElseExpression(exprs[0]);
+        }
+        
+        newCaseExpr.setType(function.getType());
+        return newCaseExpr;
+	}
+	
+    private static String convertString(String string) {
+        /*
+         * if there are no characters in the compare string we designate that as
+         * an indication of null.  ie if the decode string looks like this:
+         *
+         * "'this', 1,,'null'"
+         *
+         * Then if the value in the first argument is null then the String 'null' is
+         * returned from the function.
+         */
+        if (string.equals("")) { //$NON-NLS-1$
+            return null;
+        }
+
+        /*
+         * we also allow the use of the keyword null in the decode string.  if it
+         * wished to match on the string 'null' then the string must be qualified by
+         * ' designators.
+         */
+         if(string.equalsIgnoreCase("null")){ //$NON-NLS-1$
+            return null;
+         }
+
+        /*
+         * Here we check to see if the String in the decode String submitted
+         * was surrounded by String literal characters. In this case we strip
+         * these literal characters from the String.
+         */
+        if ((string.startsWith("\"") && string.endsWith("\"")) //$NON-NLS-1$ //$NON-NLS-2$
+            || (string.startsWith("'") && string.endsWith("'"))) { //$NON-NLS-1$ //$NON-NLS-2$
+            if (string.length() == 2) {
+                /*
+                 * This is an indication that the desired string to be compared is
+                 * the "" empty string, so we return it as such.
+                 */
+                string = ""; //$NON-NLS-1$
+            } else if (!string.equalsIgnoreCase("'") && !string.equalsIgnoreCase("\"")){ //$NON-NLS-1$ //$NON-NLS-2$
+                string = string.substring(1);
+                string = string.substring(0, string.length()-1);
+            }
+        }
+
+        return string;
+    }
+	
+    private Expression rewriteCaseExpression(CaseExpression expr)
+        throws TeiidComponentException, TeiidProcessingException{
+    	List<CompareCriteria> whens = new ArrayList<CompareCriteria>(expr.getWhenCount());
+    	for (Expression expression: (List<Expression>)expr.getWhen()) {
+    		whens.add(new CompareCriteria((Expression)expr.getExpression().clone(), CompareCriteria.EQ, expression));
+    	}
+    	SearchedCaseExpression sce = new SearchedCaseExpression(whens, expr.getThen());
+    	sce.setElseExpression(expr.getElseExpression());
+    	sce.setType(expr.getType());
+    	return rewriteCaseExpression(sce);
+    }
+
+    private Expression rewriteCaseExpression(SearchedCaseExpression expr)
+        throws TeiidComponentException, TeiidProcessingException{
+        int whenCount = expr.getWhenCount();
+        ArrayList<Criteria> whens = new ArrayList<Criteria>(whenCount);
+        ArrayList<Expression> thens = new ArrayList<Expression>(whenCount);
+
+        for (int i = 0; i < whenCount; i++) {
+            
+            // Check the when to see if this CASE can be rewritten due to an always true/false when
+            Criteria rewrittenWhen = rewriteCriteria(expr.getWhenCriteria(i));
+            if(rewrittenWhen == TRUE_CRITERIA) {
+                // WHEN is always true, so just return the THEN
+                return rewriteExpressionDirect(expr.getThenExpression(i));
+            }
+            if (rewrittenWhen == FALSE_CRITERIA || rewrittenWhen == UNKNOWN_CRITERIA) {
+            	continue;
+            }
+            
+            whens.add(rewrittenWhen);
+            thens.add(rewriteExpressionDirect(expr.getThenExpression(i)));
+        }
+
+        if (expr.getElseExpression() != null) {
+        	expr.setElseExpression(rewriteExpressionDirect(expr.getElseExpression()));
+        }
+        
+        Expression elseExpr = expr.getElseExpression();
+        if(whens.size() == 0) {
+            // No WHENs left, so just return the ELSE
+            if(elseExpr == null) {
+                // No else, no valid whens, just return null constant typed same as CASE
+                return new Constant(null, expr.getType());
+            } 
+
+            // Rewrite the else and return
+            return elseExpr;
+        }
+        
+        expr.setWhen(whens, thens);
+        
+        /* optimization for case 5413: 
+         *   If all of the remaining 'thens' and the 'else' evaluate to the same value, 
+         *     just return the 'else' expression.
+         */
+        
+        if ( elseExpr != null ) {
+            boolean bAllMatch = true;
+
+            for (int i = 0; i < whenCount; i++) {
+                if ( !thens.get( i ).equals(elseExpr) ) {
+                    bAllMatch = false;
+                    break;
+                }
+            }
+            
+            if ( bAllMatch ) {
+                return elseExpr;
+            }
+        }
+        
+        return expr;
+    }
+        
+    private Command rewriteExec(StoredProcedure storedProcedure) throws TeiidComponentException, TeiidProcessingException{
+        //After this method, no longer need to display named parameters
+        storedProcedure.setDisplayNamedParameters(false);
+        
+        for (SPParameter param : storedProcedure.getInputParameters()) {
+            if (!processing) {
+            	param.setExpression(rewriteExpressionDirect(param.getExpression()));
+            } else if (!(param.getExpression() instanceof Constant)) {
+            	param.setExpression(new Constant(this.evaluator.evaluate(param.getExpression(), null), param.getClassType()));
+            }
+        }
+        return storedProcedure;
+    }
+
+	private Insert rewriteInsert(Insert insert) throws TeiidComponentException, TeiidProcessingException{
+        
+        if ( insert.getQueryExpression() != null ) {
+        	insert.setQueryExpression((QueryCommand)rewriteCommand(insert.getQueryExpression(), true));
+        	return correctDatatypes(insert);
+        }
+        // Evaluate any function / constant trees in the insert values
+        List expressions = insert.getValues();
+        List evalExpressions = new ArrayList(expressions.size());
+        Iterator expIter = expressions.iterator();
+        while(expIter.hasNext()) {
+            Expression exp = (Expression) expIter.next();
+            evalExpressions.add( rewriteExpressionDirect( exp ));
+        }
+
+        insert.setValues(evalExpressions);        
+		return insert;
+	}
+
+    public static Query createInlineViewQuery(GroupSymbol group,
+                                               Command nested,
+                                               QueryMetadataInterface metadata,
+                                               List<SingleElementSymbol> actualSymbols) throws QueryMetadataException,
+                                                                  QueryResolverException,
+                                                                  TeiidComponentException {
+        Query query = new Query();
+        Select select = new Select();
+        query.setSelect(select);
+        From from = new From();
+        GroupSymbol inlineGroup = new GroupSymbol(group.getName().replace('.', '_') + "_1"); //$NON-NLS-1$
+        from.addClause(new UnaryFromClause(inlineGroup)); 
+        TempMetadataStore store = new TempMetadataStore();
+        TempMetadataAdapter tma = new TempMetadataAdapter(metadata, store);
+        if (nested instanceof QueryCommand) {
+	        Query firstProject = ((QueryCommand)nested).getProjectedQuery(); 
+	        makeSelectUnique(firstProject.getSelect(), false);
+        }
+        store.addTempGroup(inlineGroup.getName(), nested.getProjectedSymbols());
+        inlineGroup.setMetadataID(store.getTempGroupID(inlineGroup.getName()));
+        
+        List<Class<?>> actualTypes = new ArrayList<Class<?>>(nested.getProjectedSymbols().size());
+        for (SingleElementSymbol ses : actualSymbols) {
+            actualTypes.add(ses.getType());
+        }
+        List<SingleElementSymbol> selectSymbols = SetQuery.getTypedProjectedSymbols(ResolverUtil.resolveElementsInGroup(inlineGroup, tma), actualTypes, tma);
+        Iterator<SingleElementSymbol> iter = actualSymbols.iterator();
+        for (SingleElementSymbol ses : selectSymbols) {
+        	ses = (SingleElementSymbol)ses.clone();
+        	SingleElementSymbol actual = iter.next();
+        	if (!ses.getShortCanonicalName().equals(actual.getShortCanonicalName())) {
+	        	if (ses instanceof AliasSymbol) {
+	        		((AliasSymbol)ses).setName(actual.getShortName());
+	        	} else {
+	        		ses = new AliasSymbol(actual.getShortName(), ses);
+	        	}
+        	}
+			select.addSymbol(ses);
+		}
+        query.setFrom(from); 
+        QueryResolver.resolveCommand(query, tma);
+        query.setOption(nested.getOption());
+        from.getClauses().clear();
+        SubqueryFromClause sqfc = new SubqueryFromClause(inlineGroup.getName());
+        sqfc.setCommand(nested);
+        sqfc.getGroupSymbol().setMetadataID(inlineGroup.getMetadataID());
+        from.addClause(sqfc);
+        //copy the metadata onto the new query so that temp metadata adapters will be used in later calls
+        query.getTemporaryMetadata().putAll(store.getData()); 
+        return query;
+    }    
+    
+    public static void makeSelectUnique(Select select, boolean expressionSymbolsOnly) {
+        
+        select.setSymbols(select.getProjectedSymbols());
+        
+        List symbols = select.getSymbols();
+        
+        HashSet<String> uniqueNames = new HashSet<String>();
+        
+        for(int i = 0; i < symbols.size(); i++) {
+            
+            SingleElementSymbol symbol = (SingleElementSymbol)symbols.get(i);
+            
+            String baseName = symbol.getShortCanonicalName(); 
+            String name = baseName;
+
+            int exprID = 0;
+            while (true) {
+                if (uniqueNames.add(name)) {
+                    break;
+                }
+                name = baseName + '_' + (exprID++);
+            }
+            
+            if (expressionSymbolsOnly && !(symbol instanceof ExpressionSymbol)) {
+                continue;
+            }
+            
+            boolean hasAlias = false;
+            // Strip alias if it exists
+            if(symbol instanceof AliasSymbol) {
+                symbol = ((AliasSymbol)symbol).getSymbol();
+                hasAlias = true;
+            }
+            
+            if (((symbol instanceof ExpressionSymbol) && !hasAlias) || !name.equalsIgnoreCase(baseName)) {
+                symbols.set(i, new AliasSymbol(name, symbol));
+            }
+        }
+    }
+
+	private Update rewriteUpdate(Update update) throws TeiidComponentException, TeiidProcessingException{
+		if (commandType == Command.TYPE_UPDATE && variables != null) {
+	        SetClauseList newChangeList = new SetClauseList();
+	        for (SetClause entry : update.getChangeList().getClauses()) {
+	            Expression rightExpr = entry.getValue();
+	            boolean retainChange = checkInputVariables(rightExpr);
+	            if (retainChange) {
+	                newChangeList.addClause(entry.getSymbol(), entry.getValue());
+	            }
+	        }
+	        update.setChangeList(newChangeList);
+        }
+
+		// Evaluate any function on the right side of set clauses
+        for (SetClause entry : update.getChangeList().getClauses()) {
+        	entry.setValue(rewriteExpressionDirect(entry.getValue()));
+        }
+
+		// Rewrite criteria
+		Criteria crit = update.getCriteria();
+		if(crit != null) {
+			update.setCriteria(rewriteCriteria(crit));
+		}
+
+		return update;
+	}
+	
+    /**
+     * Checks variables in an expression, if the variables are INPUT variables and if
+     * none of them are changing, then this method returns a false, if all of them
+     * are changing this returns a true, if some are changing and some are not, then
+     * that is an invalid case and the method adds to the list of invalid variables.
+     * @throws TeiidComponentException, MetaMatrixProcessingException
+     */
+    private boolean checkInputVariables(Expression expr) throws TeiidComponentException, TeiidProcessingException{
+        Boolean result = null;
+        for (ElementSymbol var : ElementCollectorVisitor.getElements(expr, false)) {
+            String grpName = var.getGroupSymbol().getName();
+            if (var.isExternalReference() && grpName.equalsIgnoreCase(ProcedureReservedWords.INPUTS)) {
+                
+                String changingKey = ProcedureReservedWords.CHANGING + ElementSymbol.SEPARATOR + var.getShortCanonicalName();
+                
+                Boolean changingValue = (Boolean)((Constant)variables.get(changingKey)).getValue();
+                
+                if (result == null) {
+                    result = changingValue;
+                } else if (!result.equals(changingValue)) {
+                	throw new QueryValidatorException(QueryPlugin.Util.getString("VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state", expr)); //$NON-NLS-1$
+                }
+            }
+        }
+        
+        if (result != null) {
+            return result.booleanValue();
+        }
+        
+        return true;
+    }
+
+	private Delete rewriteDelete(Delete delete) throws TeiidComponentException, TeiidProcessingException{
+		// Rewrite criteria
+		Criteria crit = delete.getCriteria();
+		if(crit != null) {
+			delete.setCriteria(rewriteCriteria(crit));
+		}
+
+		return delete;
+	}
+    
+    private Limit rewriteLimitClause(Limit limit) throws TeiidComponentException, TeiidProcessingException{
+        if (limit.getOffset() != null) {
+            limit.setOffset(rewriteExpressionDirect(limit.getOffset()));
+        }
+        if (limit.getRowLimit() != null) {
+            limit.setRowLimit(rewriteExpressionDirect(limit.getRowLimit()));
+        }
+        return limit;
+    }
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,274 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.sql.visitor;
-
-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.teiid.core.util.Assertion;
-import org.teiid.query.sql.lang.BetweenCriteria;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.proc.CriteriaSelector;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.Reference;
-
-
-/**
- * <p> This class is used to translate criteria specified on the user's update command against
- * the virtual group, the elements on this criteria are replaced by elements on the query
- * transformation that defines the virtual group. Parts of the criteria are selectively translated
- * if a CriteriaSelector is specified, also if the user explicty defines translations for some
- * of the elements those translations override any symbol mappings.</p>
- */
-public class CriteriaTranslatorVisitor extends ExpressionMappingVisitor {
-
-	// criteria selector specified on the TranslateCriteria obj
-	private CriteriaSelector selector;
-
-	// translation in for of CompareCriteria objs on the TranslateCriteria obj
-	private Collection translations;
-
-	// list of translated criteria
-	private List<Criteria> translatedCriteria = new ArrayList<Criteria>();
-	
-	private Map<ElementSymbol, Reference> implicitParams = new HashMap<ElementSymbol, Reference>();
-
-    /**
-     * <p> This constructor initialises the visitor</p>
-     */
-    public CriteriaTranslatorVisitor() {
-    	this(null);
-    }
-
-    /**
-     * <p> This constructor initializes this object by setting the symbolMap.</p>
-     * @param symbolMap A map of virtual elements to their counterparts in transform
-     * defining the virtual group
-     */
-    public CriteriaTranslatorVisitor(Map symbolMap) {
-        super(symbolMap);
-        Assertion.isNotNull(symbolMap);
-    }
-
-	/**
-	 * <p>Set the criteria selector used to restrict the part of the criteria that needs to be
-	 * translated.</p>
-	 * @param selector The <code>CriteriaSelector</code> on the <code>TranslateCriteria</code>
-	 * object
-	 */
-    public void setCriteriaSelector(CriteriaSelector selector) {
-    	this.selector = selector;
-    }
-
-	/**
-	 * <p> Set the translations to be used to replace elements on the user's command against
-	 * the virtual group.</p>
-     * @param translations Collection of <code>ComapreCriteria</code> objects used to
-     * specify translations
-     */
-    public void setTranslations(Collection translations) {
-    	this.translations = translations;
-    }
-
-    // ############### Visitor methods for language objects ##################
-
-    /**
-     * <p> This method updates the <code>BetweenCriteria</code> object it receives as an
-     * argument by replacing the virtual elements present in the expressions in the
-     * function with translated expressions.</p>
-     * @param obj The BetweenCriteria object to be updated with translated expressions
-     */
-    public void visit(BetweenCriteria obj) {
-        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.BETWEEN)) {
-            return;
-        }
-        super.visit(obj);
-        translatedCriteria.add(obj);
-    }
-    
-    /**
-     * <p> This method updates the <code>CompareCriteria</code> object it receives as an
-     * argument by replacing the virtual elements present in the expressions in the
-     * function with translated expressions.</p>
-     * @param obj The CompareCriteria object to be updated with translated expressions
-     */
-    public void visit(CompareCriteria obj) {
-        
-        if (!selectorContainsCriteriaElements(obj, obj.getOperator())) {
-            return;
-        }
-
-        super.visit(obj);
-    	translatedCriteria.add(obj);
-    }
-
-    /**
-     * <p> This method updates the <code>IsNullCriteria</code> object it receives as an
-     * argument by replacing the virtual elements present in the expressions in the
-     * function with translated expressions.</p>
-     * @param obj The IsNullCriteria object to be updated with translated expressions
-     */
-    public void visit(IsNullCriteria obj) {
-
-        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.IS_NULL)) {
-            return;
-        }
-        super.visit(obj);
-        translatedCriteria.add(obj);
-    }
-
-    /**
-     * <p> This method updates the <code>MatchCriteria</code> object it receives as an
-     * argument by replacing the virtual elements present in the expressions in the
-     * function with translated expressions</p>
-     * @param obj The SetCriteria object to be updated with translated expressions
-     */
-    public void visit(MatchCriteria obj) {
-        
-        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.LIKE)) {
-            return;
-        }
-
-        super.visit(obj);
-    	translatedCriteria.add(obj);
-    }
-    
-    /**
-     * <p> This method updates the <code>SetCriteria</code> object it receives as an
-     * argument by replacing the virtual elements present in the expressions in the
-     * function with translated expressions</p>
-     * @param obj The SetCriteria object to be updated with translated expressions
-     */
-    public void visit(SetCriteria obj) {
-        
-        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.IN)) {
-            return;
-        }
-        
-        super.visit(obj);
-    	translatedCriteria.add(obj);
-    }
-
-    /**
-     * <p> This method updates the <code>SetCriteria</code> object it receives as an
-     * argument by replacing the virtual elements present in the expressions in the
-     * function with translated expressions</p>
-     * @param obj The SetCriteria object to be updated with translated expressions
-     */
-    public void visit(DependentSetCriteria obj) {
-        
-        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.IN)) {
-            return;
-        }
-        
-        super.visit(obj);
-        translatedCriteria.add(obj);
-    }
-
-    /* ############### Helper Methods ##################   */    
-    
-    private boolean selectorContainsCriteriaElements(Criteria criteria, int criteriaType) {
-        int selectorType = selector.getSelectorType();
-        if(selectorType!= CriteriaSelector.NO_TYPE && selectorType != criteriaType) {
-            return false;
-        } else if(selector.hasElements()) {                
-            Iterator selectElmnIter = selector.getElements().iterator();
-            Collection<ElementSymbol> critElmnts = ElementCollectorVisitor.getElements(criteria, true);
-            while(selectElmnIter.hasNext()) {
-                ElementSymbol selectElmnt = (ElementSymbol) selectElmnIter.next();
-                if(critElmnts.contains(selectElmnt)) {
-                    return true;
-                }
-            }
-            return false;
-        }
-        return true;
-    }
-    
-    @Override
-    public Expression replaceExpression(Expression obj) {
-    	if (this.translations != null && obj instanceof ElementSymbol) {
-			Iterator transIter = this.translations.iterator();
-			while(transIter.hasNext()) {
-				CompareCriteria compCrit = (CompareCriteria) transIter.next();
-				Collection<ElementSymbol> leftElmnts = ElementCollectorVisitor.getElements(compCrit.getLeftExpression(), true);
-				// there is always only one element
-				ElementSymbol element = leftElmnts.iterator().next();
-				if(obj.equals(element)) {
-					return compCrit.getRightExpression();
-				}
-			}
-     	}
-    	/*
-    	 * Special handling for references in translated criteria.
-    	 * We need to create a locally valid reference name.
-    	 */
-    	if (obj instanceof Reference) {
-    		Reference implicit = (Reference)obj;
-    		ElementSymbol key = null;
-    		if (implicit.isPositional()) {
-    			key = new ElementSymbol("$INPUT." + implicit.getContextSymbol()); //$NON-NLS-1$
-    		} else {
-    			key = new ElementSymbol("$INPUT." + implicit.getExpression().getName()); //$NON-NLS-1$
-    		}
-    		key.setType(implicit.getType());
-    		this.implicitParams.put(key, implicit);
-    		return new Reference(key);
-    	}
-    	return super.replaceExpression(obj);
-    }
-
-    /**
-     * <p>Gets the criteria translated by this visitor, differrent parts of the user's
-     * criteria are translated and they are combined as a <code>CompoundCriteria</code>
-     * using an AND operator. Returns a null if no part of the user's criteria could
-     * be translated.</p>
-     * @return The criteria after vistor completes translation of the criteria on the
-     * virtual group
-     */
-    public Criteria getTranslatedCriteria() {
-    	if(translatedCriteria.size() > 0) {
-    		if(translatedCriteria.size() == 1) {
-    			return translatedCriteria.get(0);
-    		}
-   			return new CompoundCriteria(CompoundCriteria.AND, translatedCriteria);
-    	}
-   		return null;
-    }
-    
-    public Map<ElementSymbol, Reference> getImplicitParams() {
-		return implicitParams;
-	}
-    
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,263 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.sql.visitor;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.util.Assertion;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.sql.lang.BetweenCriteria;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.navigator.PreOrderNavigator;
+import org.teiid.query.sql.proc.CriteriaSelector;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.Reference;
+
+
+/**
+ * <p> This class is used to translate criteria specified on the user's update command against
+ * the virtual group, the elements on this criteria are replaced by elements on the query
+ * transformation that defines the virtual group. Parts of the criteria are selectively translated
+ * if a CriteriaSelector is specified, also if the user explicty defines translations for some
+ * of the elements those translations override any symbol mappings.</p>
+ */
+public class CriteriaTranslatorVisitor extends ExpressionMappingVisitor {
+	
+	class CriteriaTranslatorNavigator extends PreOrderNavigator {
+
+		public CriteriaTranslatorNavigator() {
+			super(CriteriaTranslatorVisitor.this);
+		}
+		
+	    /**
+	     * <p> This method updates the <code>BetweenCriteria</code> object it receives as an
+	     * argument by replacing the virtual elements present in the expressions in the
+	     * function with translated expressions.</p>
+	     * @param obj The BetweenCriteria object to be updated with translated expressions
+	     */
+	    public void visit(BetweenCriteria obj) {
+	        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.BETWEEN)) {
+	        	throw new TeiidRuntimeException(new QueryValidatorException(QueryPlugin.Util.getString("Translate.error", obj, selector))); //$NON-NLS-1$ 
+	        }
+	        super.visit(obj);
+	    }
+	    
+	    /**
+	     * <p> This method updates the <code>CompareCriteria</code> object it receives as an
+	     * argument by replacing the virtual elements present in the expressions in the
+	     * function with translated expressions.</p>
+	     * @param obj The CompareCriteria object to be updated with translated expressions
+	     */
+	    public void visit(CompareCriteria obj) {
+	        
+	        if (!selectorContainsCriteriaElements(obj, obj.getOperator())) {
+	        	throw new TeiidRuntimeException(new QueryValidatorException(QueryPlugin.Util.getString("Translate.error", obj, selector))); //$NON-NLS-1$ 
+	        }
+
+	        super.visit(obj);
+	    }
+
+	    /**
+	     * <p> This method updates the <code>IsNullCriteria</code> object it receives as an
+	     * argument by replacing the virtual elements present in the expressions in the
+	     * function with translated expressions.</p>
+	     * @param obj The IsNullCriteria object to be updated with translated expressions
+	     */
+	    public void visit(IsNullCriteria obj) {
+
+	        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.IS_NULL)) {
+	        	throw new TeiidRuntimeException(new QueryValidatorException(QueryPlugin.Util.getString("Translate.error", obj, selector))); //$NON-NLS-1$ 
+	        }
+	        super.visit(obj);
+	    }
+
+	    /**
+	     * <p> This method updates the <code>MatchCriteria</code> object it receives as an
+	     * argument by replacing the virtual elements present in the expressions in the
+	     * function with translated expressions</p>
+	     * @param obj The SetCriteria object to be updated with translated expressions
+	     */
+	    public void visit(MatchCriteria obj) {
+	        
+	        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.LIKE)) {
+	        	throw new TeiidRuntimeException(new QueryValidatorException(QueryPlugin.Util.getString("Translate.error", obj, selector))); //$NON-NLS-1$ 
+	        }
+
+	        super.visit(obj);
+	    }
+	    
+	    /**
+	     * <p> This method updates the <code>SetCriteria</code> object it receives as an
+	     * argument by replacing the virtual elements present in the expressions in the
+	     * function with translated expressions</p>
+	     * @param obj The SetCriteria object to be updated with translated expressions
+	     */
+	    public void visit(SetCriteria obj) {
+	        
+	        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.IN)) {
+	        	throw new TeiidRuntimeException(new QueryValidatorException(QueryPlugin.Util.getString("Translate.error", obj, selector))); //$NON-NLS-1$
+	        }
+	        
+	        super.visit(obj);
+	    }
+
+	    /**
+	     * <p> This method updates the <code>SetCriteria</code> object it receives as an
+	     * argument by replacing the virtual elements present in the expressions in the
+	     * function with translated expressions</p>
+	     * @param obj The SetCriteria object to be updated with translated expressions
+	     */
+	    public void visit(DependentSetCriteria obj) {
+	        
+	        if (!selectorContainsCriteriaElements(obj, CriteriaSelector.IN)) {
+	        	throw new TeiidRuntimeException(new QueryValidatorException(QueryPlugin.Util.getString("Translate.error", obj, selector))); //$NON-NLS-1$
+	        }
+	        
+	        super.visit(obj);
+	    }
+		
+	}
+
+	// criteria selector specified on the TranslateCriteria obj
+	private CriteriaSelector selector;
+
+	// translation in for of CompareCriteria objs on the TranslateCriteria obj
+	private Collection translations;
+
+	private Map<ElementSymbol, Reference> implicitParams = new HashMap<ElementSymbol, Reference>();
+
+    /**
+     * <p> This constructor initialises the visitor</p>
+     */
+    public CriteriaTranslatorVisitor() {
+    	this(null);
+    }
+
+    /**
+     * <p> This constructor initializes this object by setting the symbolMap.</p>
+     * @param symbolMap A map of virtual elements to their counterparts in transform
+     * defining the virtual group
+     */
+    public CriteriaTranslatorVisitor(Map symbolMap) {
+        super(symbolMap);
+        Assertion.isNotNull(symbolMap);
+    }
+
+	/**
+	 * <p>Set the criteria selector used to restrict the part of the criteria that needs to be
+	 * translated.</p>
+	 * @param selector The <code>CriteriaSelector</code> on the <code>TranslateCriteria</code>
+	 * object
+	 */
+    public void setCriteriaSelector(CriteriaSelector selector) {
+    	this.selector = selector;
+    }
+
+	/**
+	 * <p> Set the translations to be used to replace elements on the user's command against
+	 * the virtual group.</p>
+     * @param translations Collection of <code>ComapreCriteria</code> objects used to
+     * specify translations
+     */
+    public void setTranslations(Collection translations) {
+    	this.translations = translations;
+    }
+
+    /* ############### Helper Methods ##################   */    
+    
+    private boolean selectorContainsCriteriaElements(Criteria criteria, int criteriaType) {
+        int selectorType = selector.getSelectorType();
+        if(selectorType!= CriteriaSelector.NO_TYPE && selectorType != criteriaType) {
+            return false;
+        } else if(selector.hasElements()) {                
+            Iterator selectElmnIter = selector.getElements().iterator();
+            Collection<ElementSymbol> critElmnts = ElementCollectorVisitor.getElements(criteria, true);
+            while(selectElmnIter.hasNext()) {
+                ElementSymbol selectElmnt = (ElementSymbol) selectElmnIter.next();
+                if(critElmnts.contains(selectElmnt)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+        return true;
+    }
+    
+    @Override
+    public Expression replaceExpression(Expression obj) {
+    	if (this.translations != null && obj instanceof ElementSymbol) {
+			Iterator transIter = this.translations.iterator();
+			while(transIter.hasNext()) {
+				CompareCriteria compCrit = (CompareCriteria) transIter.next();
+				Collection<ElementSymbol> leftElmnts = ElementCollectorVisitor.getElements(compCrit.getLeftExpression(), true);
+				// there is always only one element
+				ElementSymbol element = leftElmnts.iterator().next();
+				if(obj.equals(element)) {
+					return compCrit.getRightExpression();
+				}
+			}
+     	}
+    	/*
+    	 * Special handling for references in translated criteria.
+    	 * We need to create a locally valid reference name.
+    	 */
+    	if (obj instanceof Reference) {
+    		Reference implicit = (Reference)obj;
+    		ElementSymbol key = null;
+    		if (implicit.isPositional()) {
+    			key = new ElementSymbol("$INPUT." + implicit.getContextSymbol()); //$NON-NLS-1$
+    		} else {
+    			key = new ElementSymbol("$INPUT." + implicit.getExpression().getName()); //$NON-NLS-1$
+    		}
+    		key.setType(implicit.getType());
+    		this.implicitParams.put(key, implicit);
+    		return new Reference(key);
+    	}
+    	return super.replaceExpression(obj);
+    }
+
+    public Map<ElementSymbol, Reference> getImplicitParams() {
+		return implicitParams;
+	}
+    
+    public void translate(Criteria crit) throws QueryValidatorException {
+    	CriteriaTranslatorNavigator nav = new CriteriaTranslatorNavigator();
+    	try {
+    		crit.acceptVisitor(nav);
+    	} catch (TeiidRuntimeException e) {
+    		throw (QueryValidatorException)e.getCause();
+    	}
+    }
+    
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
===================================================================
--- branches/7.2.x/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,602 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.tempdata;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Executor;
-import java.util.concurrent.FutureTask;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryProcessingException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.cache.Cache;
-import org.teiid.cache.CacheConfiguration;
-import org.teiid.cache.CacheFactory;
-import org.teiid.cache.CacheConfiguration.Policy;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.core.CoreConstants;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.HashCodeUtil;
-import org.teiid.core.util.StringUtil;
-import org.teiid.dqp.internal.process.CachedResults;
-import org.teiid.dqp.internal.process.SessionAwareCache;
-import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
-import org.teiid.language.SQLConstants.Reserved;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.function.metadata.FunctionMethod;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.optimizer.relational.RelationalPlanner;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.query.processor.BatchCollector;
-import org.teiid.query.processor.CollectionTupleSource;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.lang.CacheHint;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.Create;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.Drop;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.Option;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.navigator.PostOrderNavigator;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
-import org.teiid.query.tempdata.TempTableStore.MatState;
-import org.teiid.query.tempdata.TempTableStore.MatTableInfo;
-import org.teiid.query.util.CommandContext;
-import org.teiid.vdb.runtime.VDBKey;
-
-/**
- * This proxy ProcessorDataManager is used to handle temporary tables.
- * 
- * This isn't handled as a connector because of the temporary metadata and 
- * the create/drop handling (which doesn't have push down support)
- */
-public class TempTableDataManager implements ProcessorDataManager {
-	
-    private static final String REFRESHMATVIEWROW = ".refreshmatviewrow"; //$NON-NLS-1$
-	private static final String REFRESHMATVIEW = ".refreshmatview"; //$NON-NLS-1$
-	private static final String CODE_PREFIX = "#CODE_"; //$NON-NLS-1$
-	
-	private ProcessorDataManager processorDataManager;
-    private BufferManager bufferManager;
-	private SessionAwareCache<CachedResults> cache;
-    private Executor executor;
-    
-    private static class MatTableKey implements Serializable {
-		private static final long serialVersionUID = 5481692896572663992L;
-		String name;
-    	VDBKey vdb;
-    	
-    	@Override
-    	public int hashCode() {
-    		return HashCodeUtil.hashCode(name.hashCode(), vdb);
-    	}
-    	
-    	@Override
-    	public boolean equals(Object obj) {
-    		if (obj == this) {
-    			return true;
-    		}
-    		if (!(obj instanceof MatTableKey)) {
-    			return false;
-    		}
-    		MatTableKey other = (MatTableKey)obj;
-    		return this.name.equals(other.name) && this.vdb.equals(other.vdb);
-    	}
-    }
-    
-    private static class MatTableEntry implements Serializable {
-		private static final long serialVersionUID = 8559613701442751579L;
-    	long lastUpdate = System.currentTimeMillis();
-    	boolean valid;
-    }
-    
-    private Cache<MatTableKey, MatTableEntry> tables;
-    private SessionAwareCache<CachedResults> distributedCache;
-
-    public TempTableDataManager(ProcessorDataManager processorDataManager, BufferManager bufferManager, 
-    		Executor executor, SessionAwareCache<CachedResults> cache, SessionAwareCache<CachedResults> distibutedCache, CacheFactory cacheFactory){
-        this.processorDataManager = processorDataManager;
-        this.bufferManager = bufferManager;
-        this.executor = executor;
-        this.cache = cache;
-        this.distributedCache = distibutedCache;
-        if (distibutedCache != null) {
-	        CacheConfiguration cc = new CacheConfiguration(Policy.LRU, -1, -1);
-	        tables = cacheFactory.get(Cache.Type.MATTABLES, cc);
-        }
-    }
-    
-	public TupleSource registerRequest(
-		CommandContext context,
-		Command command,
-		String modelName,
-		String connectorBindingId, int nodeID)
-		throws TeiidComponentException, TeiidProcessingException {          
-
-		TempTableStore tempTableStore = context.getTempTableStore();
-        if(tempTableStore != null) {
-            TupleSource result = registerRequest(context, modelName, command);
-            if (result != null) {
-            	return result;
-            }
-        }
-        return this.processorDataManager.registerRequest(context, command, modelName, connectorBindingId, nodeID);
-	}
-	        
-    TupleSource registerRequest(CommandContext context, String modelName, Command command) throws TeiidComponentException, TeiidProcessingException {
-    	TempTableStore contextStore = context.getTempTableStore();
-        if (command instanceof Query) {
-            Query query = (Query)command;
-            return registerQuery(context, contextStore, query);
-        }
-        if (command instanceof ProcedureContainer) {
-        	if (command instanceof StoredProcedure) {
-        		StoredProcedure proc = (StoredProcedure)command;
-        		if (CoreConstants.SYSTEM_ADMIN_MODEL.equals(modelName)) {
-	        		TupleSource result = handleSystemProcedures(context, proc);
-	        		if (result != null) {
-	        			return result;
-	        		}
-        		} else if (proc.getGroup().isGlobalTable()) {
-        			return handleCachedProcedure(context, proc);
-        		}
-        		return null; //it's not a stored procedure we want to handle
-        	}
-        	
-        	GroupSymbol group = ((ProcedureContainer)command).getGroup();
-        	if (!group.isTempGroupSymbol()) {
-        		return null;
-        	}
-        	final String groupKey = group.getNonCorrelationName().toUpperCase();
-            final TempTable table = contextStore.getOrCreateTempTable(groupKey, command, bufferManager, false);
-        	if (command instanceof Insert) {
-        		Insert insert = (Insert)command;
-        		TupleSource ts = insert.getTupleSource();
-        		if (ts == null) {
-        			List<Object> values = new ArrayList<Object>(insert.getValues().size());
-        			for (Expression expr : (List<Expression>)insert.getValues()) {
-        				values.add(Evaluator.evaluate(expr));
-					}
-        			ts = new CollectionTupleSource(Arrays.asList(values).iterator());
-        		}
-        		return table.insert(ts, insert.getVariables());
-        	}
-        	if (command instanceof Update) {
-        		final Update update = (Update)command;
-        		final Criteria crit = update.getCriteria();
-        		return table.update(crit, update.getChangeList());
-        	}
-        	if (command instanceof Delete) {
-        		final Delete delete = (Delete)command;
-        		final Criteria crit = delete.getCriteria();
-        		if (crit == null) {
-        			//because we are non-transactional, just use a truncate
-        			int rows = table.truncate();
-                    return CollectionTupleSource.createUpdateCountTupleSource(rows);
-        		}
-        		return table.delete(crit);
-        	}
-        }
-    	if (command instanceof Create) {
-    		Create create = (Create)command;
-    		String tempTableName = create.getTable().getCanonicalName();
-    		if (contextStore.hasTempTable(tempTableName)) {
-                throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableStore.table_exist_error", tempTableName));//$NON-NLS-1$
-            }
-    		contextStore.addTempTable(tempTableName, create, bufferManager, true);
-            return CollectionTupleSource.createUpdateCountTupleSource(0);	
-    	}
-    	if (command instanceof Drop) {
-    		String tempTableName = ((Drop)command).getTable().getCanonicalName();
-    		contextStore.removeTempTableByName(tempTableName);
-            return CollectionTupleSource.createUpdateCountTupleSource(0);
-    	}
-        return null;
-    }
-
-	private TupleSource handleCachedProcedure(CommandContext context,
-			StoredProcedure proc) throws TeiidComponentException,
-			QueryMetadataException, TeiidProcessingException {
-		String fullName = context.getMetadata().getFullName(proc.getProcedureID());
-		LogManager.logDetail(LogConstants.CTX_DQP, "processing cached procedure request for", fullName); //$NON-NLS-1$
-		LinkedList<Object> vals = new LinkedList<Object>();
-		for (SPParameter param : proc.getInputParameters()) {
-			vals.add(((Constant)param.getExpression()).getValue());
-		}
-		//collapse the hash to single byte for the key to restrict the possible results to 256
-		int hash = vals.hashCode();
-		hash |= (hash >>> 16);
-		hash |= (hash >>> 8);
-		hash &= 0x000000ff;
-		CacheID cid = new CacheID(new ParseInfo(), fullName + hash, context.getVdbName(), 
-				context.getVdbVersion(), context.getConnectionID(), context.getUserName());
-		cid.setParameters(vals);
-		CachedResults results = cache.get(cid);
-		if (results != null) {
-			TupleBuffer buffer = results.getResults();
-			return buffer.createIndexedTupleSource();
-		}
-		//construct a query with a no cache hint
-		//note that it's safe to use the stringified form of the parameters because
-		//it's not possible to use xml/clob/blob/object
-		CacheHint hint = proc.getCacheHint();
-		proc.setCacheHint(null);
-		Option option = new Option();
-		option.setNoCache(true);
-		option.addNoCacheGroup(fullName);
-		proc.setOption(option);
-		int determinismLevel = context.resetDeterminismLevel();
-		QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(proc.toString(), fullName.toUpperCase(), context);
-		qp.setNonBlocking(true);
-		BatchCollector bc = qp.createBatchCollector();
-		TupleBuffer tb = bc.collectTuples();
-		CachedResults cr = new CachedResults();
-		cr.setResults(tb);
-		cr.setHint(hint);
-		cache.put(cid, context.getDeterminismLevel(), cr, hint != null?hint.getTtl():null);
-		context.setDeterminismLevel(determinismLevel);
-		return tb.createIndexedTupleSource();
-	}
-
-	private TupleSource handleSystemProcedures(CommandContext context, StoredProcedure proc)
-			throws TeiidComponentException, QueryMetadataException,
-			QueryProcessingException, QueryResolverException,
-			QueryValidatorException, TeiidProcessingException,
-			ExpressionEvaluationException {
-		QueryMetadataInterface metadata = context.getMetadata();
-		TempTableStore globalStore = context.getGlobalTableStore();
-		if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEW)) {
-			Object groupID = validateMatView(metadata, proc);
-			String matViewName = metadata.getFullName(groupID);
-			String matTableName = RelationalPlanner.MAT_PREFIX+matViewName.toUpperCase();
-			LogManager.logDetail(LogConstants.CTX_MATVIEWS, "processing refreshmatview for", matViewName); //$NON-NLS-1$
-			MatTableInfo info = globalStore.getMatTableInfo(matTableName);
-			boolean invalidate = Boolean.TRUE.equals(((Constant)proc.getParameter(1).getExpression()).getValue());
-			if (invalidate) {
-				touchTable(context, matTableName, false);
-			}
-			MatState oldState = info.setState(MatState.NEEDS_LOADING, invalidate?Boolean.FALSE:null, null);
-			if (oldState == MatState.LOADING) {
-				return CollectionTupleSource.createUpdateCountTupleSource(-1);
-			}
-			GroupSymbol group = new GroupSymbol(matViewName);
-			group.setMetadataID(groupID);
-			Object matTableId = RelationalPlanner.getGlobalTempTableMetadataId(group, matTableName, context, metadata, AnalysisRecord.createNonRecordingRecord());
-			GroupSymbol matTable = new GroupSymbol(matTableName);
-			matTable.setMetadataID(matTableId);
-			int rowCount = loadGlobalTable(context, matTable, matTableName, globalStore, info, null);
-			return CollectionTupleSource.createUpdateCountTupleSource(rowCount);
-		} else if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEWROW)) {
-			Object groupID = validateMatView(metadata, proc);
-			Object pk = metadata.getPrimaryKey(groupID);
-			String matViewName = metadata.getFullName(groupID);
-			if (pk == null) {
-				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_pk", matViewName)); //$NON-NLS-1$
-			}
-			List<?> ids = metadata.getElementIDsInKey(pk);
-			if (ids.size() > 1) {
-				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_composite", matViewName)); //$NON-NLS-1$
-			}
-			String matTableName = RelationalPlanner.MAT_PREFIX+matViewName.toUpperCase();
-			MatTableInfo info = globalStore.getMatTableInfo(matTableName);
-			if (!info.isValid()) {
-				return CollectionTupleSource.createUpdateCountTupleSource(-1);
-			}
-			TempTable tempTable = globalStore.getOrCreateTempTable(matTableName, new Query(), bufferManager, false);
-			if (!tempTable.isUpdatable()) {
-				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_updatable", matViewName)); //$NON-NLS-1$
-			}
-			Constant key = (Constant)proc.getParameter(2).getExpression();
-			LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.row_refresh", matViewName, key)); //$NON-NLS-1$
-			String queryString = Reserved.SELECT + " * " + Reserved.FROM + ' ' + matViewName + ' ' + Reserved.WHERE + ' ' + //$NON-NLS-1$
-				metadata.getFullName(ids.iterator().next()) + " = ?" + ' ' + Reserved.OPTION + ' ' + Reserved.NOCACHE; //$NON-NLS-1$
-			QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(queryString, matViewName.toUpperCase(), context, key.getValue());
-			qp.setNonBlocking(true);
-			TupleSource ts = new BatchCollector.BatchProducerTupleSource(qp);
-			tempTable = globalStore.getOrCreateTempTable(matTableName, new Query(), bufferManager, false);
-			List<?> tuple = ts.nextTuple();
-			boolean delete = false;
-			if (tuple == null) {
-				delete = true;
-				tuple = Arrays.asList(key.getValue());
-			}
-			List<?> result = tempTable.updateTuple(tuple, delete);
-			//TODO: maintain a table log and distribute the events
-			return CollectionTupleSource.createUpdateCountTupleSource(result != null ? 1 : 0);
-		}
-		return null;
-	}
-
-	private Object validateMatView(QueryMetadataInterface metadata,
-			StoredProcedure proc) throws TeiidComponentException,
-			TeiidProcessingException {
-		String name = (String)((Constant)proc.getParameter(1).getExpression()).getValue();
-		try {
-			Object groupID = metadata.getGroupID(name);
-			if (!metadata.hasMaterialization(groupID) || metadata.getMaterialization(groupID) != null) {
-				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.not_implicit_matview", name)); //$NON-NLS-1$
-			}
-			return groupID;
-		} catch (QueryMetadataException e) {
-			throw new TeiidProcessingException(e);
-		}
-	}
-
-	private TupleSource registerQuery(final CommandContext context,
-			TempTableStore contextStore, Query query)
-			throws TeiidComponentException, QueryMetadataException,
-			TeiidProcessingException, ExpressionEvaluationException,
-			QueryProcessingException {
-		final GroupSymbol group = query.getFrom().getGroups().get(0);
-		if (!group.isTempGroupSymbol()) {
-			return null;
-		}
-		final String tableName = group.getNonCorrelationName().toUpperCase();
-		boolean remapColumns = !tableName.equalsIgnoreCase(group.getName());
-		TempTable table = null;
-		if (group.isGlobalTable()) {
-			final TempTableStore globalStore = context.getGlobalTableStore();
-			final MatTableInfo info = globalStore.getMatTableInfo(tableName);
-			Long loadTime = null;
-			if (this.distributedCache != null) {
-				MatTableKey key = new MatTableKey();
-				key.name = tableName;
-				key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
-				
-				MatTableEntry entry = this.tables.get(key);
-				if (entry != null && entry.lastUpdate > info.getUpdateTime() 
-						&& info.getState() != MatState.LOADING) {
-					//remote load
-					info.setState(MatState.NEEDS_LOADING, entry.valid, null);
-					loadTime = entry.lastUpdate;
-				}
-			}
-			boolean load = info.shouldLoad();
-			if (load) {
-				if (!info.isValid()) {
-					//blocking load
-					loadGlobalTable(context, group, tableName, globalStore, info, loadTime);
-				} else {
-					loadAsynch(context, group, tableName, globalStore, info, loadTime);
-				}
-			} 
-			table = globalStore.getOrCreateTempTable(tableName, query, bufferManager, false);
-		} else {
-			table = contextStore.getOrCreateTempTable(tableName, query, bufferManager, true);
-		}
-		if (remapColumns) {
-			//convert to the actual table symbols (this is typically handled by the languagebridgefactory
-			ExpressionMappingVisitor emv = new ExpressionMappingVisitor(null) {
-				@Override
-				public Expression replaceExpression(Expression element) {
-					if (element instanceof ElementSymbol) {
-						ElementSymbol es = (ElementSymbol)element;
-						((ElementSymbol) element).setName(tableName + ElementSymbol.SEPARATOR + es.getShortName());
-					}
-					return element;
-				}
-			};
-			PostOrderNavigator.doVisit(query, emv);
-		}
-		return table.createTupleSource(query.getProjectedSymbols(), query.getCriteria(), query.getOrderBy());
-	}
-
-	private void loadAsynch(final CommandContext context,
-			final GroupSymbol group, final String tableName,
-			final TempTableStore globalStore, final MatTableInfo info,
-			final Long loadTime) {
-		Callable<Integer> toCall = new Callable<Integer>() {
-			@Override
-			public Integer call() throws Exception {
-				return loadGlobalTable(context, group, tableName, globalStore, info, loadTime);
-			}
-		};
-		FutureTask<Integer> task = new FutureTask<Integer>(toCall);
-		executor.execute(task);
-	}
-
-	private int loadGlobalTable(CommandContext context,
-			GroupSymbol group, final String tableName,
-			TempTableStore globalStore, MatTableInfo info, Long loadTime)
-			throws TeiidComponentException, TeiidProcessingException {
-		LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.loading", tableName)); //$NON-NLS-1$
-		QueryMetadataInterface metadata = context.getMetadata();
-		Create create = new Create();
-		create.setTable(group);
-		List<ElementSymbol> allColumns = ResolverUtil.resolveElementsInGroup(group, metadata); 
-		create.setColumns(allColumns);
-		Object pk = metadata.getPrimaryKey(group.getMetadataID());
-		if (pk != null) {
-			List<ElementSymbol> pkColumns = resolveIndex(metadata, allColumns, pk);
-			create.getPrimaryKey().addAll(pkColumns);
-		}
-		TempTable table = globalStore.addTempTable(tableName, create, bufferManager, false);
-		table.setUpdatable(false);
-		CacheHint hint = table.getCacheHint();
-		boolean updatable = false;
-		if (hint != null) {
-			table.setPreferMemory(hint.getPrefersMemory());
-			if (hint.getTtl() != null) {
-				info.setTtl(table.getCacheHint().getTtl());
-			}
-			if (pk != null) {
-				updatable = hint.isUpdatable();
-			}
-		}
-		int rowCount = -1;
-		try {
-			String fullName = metadata.getFullName(group.getMetadataID());
-			TupleSource ts = null;
-			CacheID cid = null;
-			if (distributedCache != null) {
-				cid = new CacheID(new ParseInfo(), fullName, context.getVdbName(), 
-						context.getVdbVersion(), context.getConnectionID(), context.getUserName());
-				CachedResults cr = this.distributedCache.get(cid);
-				if (cr != null) {
-					ts = cr.getResults().createIndexedTupleSource();
-				}
-			}
-			
-			if (ts == null) {
-				//TODO: coordinate a distributed load
-				//TODO: order by primary key nulls first - then have an insert ordered optimization
-				String transformation = metadata.getVirtualPlan(group.getMetadataID()).getQuery();
-				QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(transformation, fullName, context);
-				qp.setNonBlocking(true);
-				
-				if (distributedCache != null) {
-					CachedResults cr = new CachedResults();
-					BatchCollector bc = qp.createBatchCollector();
-					TupleBuffer tb = bc.collectTuples();
-					cr.setResults(tb);
-					touchTable(context, fullName, true);
-					this.distributedCache.put(cid, FunctionMethod.VDB_DETERMINISTIC, cr, info.getTtl());
-					ts = tb.createIndexedTupleSource();
-				} else {
-					ts = new BatchCollector.BatchProducerTupleSource(qp);
-				}
-			}
-			
-			//TODO: if this insert fails, it's unnecessary to do the undo processing
-			table.insert(ts, table.getColumns());
-			rowCount = table.getRowCount();
-			//TODO: could pre-process indexes to remove overlap
-			for (Object index : metadata.getIndexesInGroup(group.getMetadataID())) {
-				List<ElementSymbol> columns = resolveIndex(metadata, allColumns, index);
-				table.addIndex(columns);
-			}
-			for (Object key : metadata.getUniqueKeysInGroup(group.getMetadataID())) {
-				List<ElementSymbol> columns = resolveIndex(metadata, allColumns, key);
-				table.addIndex(columns);
-			}
-			table.setUpdatable(updatable);
-		} catch (TeiidComponentException e) {
-			LogManager.logError(LogConstants.CTX_MATVIEWS, e, QueryPlugin.Util.getString("TempTableDataManager.failed_load", tableName)); //$NON-NLS-1$
-			throw e;
-		} catch (TeiidProcessingException e) {
-			LogManager.logError(LogConstants.CTX_MATVIEWS, e, QueryPlugin.Util.getString("TempTableDataManager.failed_load", tableName)); //$NON-NLS-1$
-			throw e;
-		} finally {
-			if (rowCount == -1) {
-				info.setState(MatState.FAILED_LOAD, null, null);
-			} else {
-				globalStore.swapTempTable(tableName, table);
-				info.setState(MatState.LOADED, true, loadTime);
-				LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.loaded", tableName, rowCount)); //$NON-NLS-1$
-			}
-		}
-		return rowCount;
-	}
-
-	private void touchTable(CommandContext context, String fullName, boolean valid) {
-		MatTableKey key = new MatTableKey();
-		key.name = fullName;
-		key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
-		MatTableEntry matTableEntry = new MatTableEntry();
-		matTableEntry.valid = valid;
-		tables.put(key, matTableEntry, null);
-	}
-
-	/**
-	 * Return a list of ElementSymbols for the given index/key object
-	 */
-	private List<ElementSymbol> resolveIndex(QueryMetadataInterface metadata,
-			List<ElementSymbol> allColumns, Object pk)
-			throws TeiidComponentException, QueryMetadataException {
-		Collection<?> pkIds = metadata.getElementIDsInKey(pk);
-		List<ElementSymbol> pkColumns = new ArrayList<ElementSymbol>(pkIds.size());
-		for (Object col : pkIds) {
-			pkColumns.add(allColumns.get(metadata.getPosition(col)-1));
-		}
-		return pkColumns;
-	}
-
-	public Object lookupCodeValue(CommandContext context, String codeTableName,
-			String returnElementName, String keyElementName, Object keyValue)
-			throws BlockedException, TeiidComponentException,
-			TeiidProcessingException {
-    	String matTableName = CODE_PREFIX + (codeTableName + ElementSymbol.SEPARATOR + keyElementName + ElementSymbol.SEPARATOR + returnElementName).toUpperCase(); 
-
-    	ElementSymbol keyElement = new ElementSymbol(matTableName + ElementSymbol.SEPARATOR + keyElementName);
-    	ElementSymbol returnElement = new ElementSymbol(matTableName + ElementSymbol.SEPARATOR + returnElementName);
-    	
-    	QueryMetadataInterface metadata = context.getMetadata();
-    	
-    	keyElement.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(metadata.getElementID(codeTableName + ElementSymbol.SEPARATOR + keyElementName))));
-    	returnElement.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(metadata.getElementID(codeTableName + ElementSymbol.SEPARATOR + returnElementName))));
-    	
-    	TempMetadataID id = context.getGlobalTableStore().getMetadataStore().getTempGroupID(matTableName);
-    	if (id == null) {
-	    	id = context.getGlobalTableStore().getMetadataStore().addTempGroup(matTableName, Arrays.asList(keyElement, returnElement), false, true);
-	    	String queryString = Reserved.SELECT + ' ' + keyElementName + " ," + returnElementName + ' ' + Reserved.FROM + ' ' + codeTableName; //$NON-NLS-1$ 
-	    	id.setQueryNode(new QueryNode(matTableName, queryString));
-	    	id.setPrimaryKey(id.getElements().subList(0, 1));
-	    	CacheHint hint = new CacheHint(true, null);
-	    	id.setCacheHint(hint);
-    	}
-    	Query query = RelationalPlanner.createMatViewQuery(id, matTableName, Arrays.asList(returnElement), true);
-    	query.setCriteria(new CompareCriteria(keyElement, CompareCriteria.EQ, new Constant(keyValue)));
-    	
-    	TupleSource ts = registerQuery(context, context.getTempTableStore(), query);
-    	List<?> row = ts.nextTuple();
-    	Object result = null;
-    	if (row != null) {
-    		result = row.get(0);
-    	}
-    	ts.closeSource();
-    	return result;
-    }
-
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java (from rev 2707, branches/7.2.x/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,605 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.tempdata;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Executor;
+import java.util.concurrent.FutureTask;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryProcessingException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.cache.Cache;
+import org.teiid.cache.CacheConfiguration;
+import org.teiid.cache.CacheFactory;
+import org.teiid.cache.CacheConfiguration.Policy;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.core.CoreConstants;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.core.util.StringUtil;
+import org.teiid.dqp.internal.process.CachedResults;
+import org.teiid.dqp.internal.process.SessionAwareCache;
+import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
+import org.teiid.language.SQLConstants.Reserved;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.function.metadata.FunctionMethod;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.optimizer.relational.RelationalPlanner;
+import org.teiid.query.parser.ParseInfo;
+import org.teiid.query.processor.BatchCollector;
+import org.teiid.query.processor.CollectionTupleSource;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.lang.CacheHint;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Create;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.Drop;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.Option;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.navigator.PostOrderNavigator;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
+import org.teiid.query.tempdata.TempTableStore.MatState;
+import org.teiid.query.tempdata.TempTableStore.MatTableInfo;
+import org.teiid.query.util.CommandContext;
+import org.teiid.vdb.runtime.VDBKey;
+
+/**
+ * This proxy ProcessorDataManager is used to handle temporary tables.
+ * 
+ * This isn't handled as a connector because of the temporary metadata and 
+ * the create/drop handling (which doesn't have push down support)
+ */
+public class TempTableDataManager implements ProcessorDataManager {
+	
+    private static final String REFRESHMATVIEWROW = ".refreshmatviewrow"; //$NON-NLS-1$
+	private static final String REFRESHMATVIEW = ".refreshmatview"; //$NON-NLS-1$
+	private static final String CODE_PREFIX = "#CODE_"; //$NON-NLS-1$
+	
+	private ProcessorDataManager processorDataManager;
+    private BufferManager bufferManager;
+	private SessionAwareCache<CachedResults> cache;
+    private Executor executor;
+    
+    private static class MatTableKey implements Serializable {
+		private static final long serialVersionUID = 5481692896572663992L;
+		String name;
+    	VDBKey vdb;
+    	
+    	@Override
+    	public int hashCode() {
+    		return HashCodeUtil.hashCode(name.hashCode(), vdb);
+    	}
+    	
+    	@Override
+    	public boolean equals(Object obj) {
+    		if (obj == this) {
+    			return true;
+    		}
+    		if (!(obj instanceof MatTableKey)) {
+    			return false;
+    		}
+    		MatTableKey other = (MatTableKey)obj;
+    		return this.name.equals(other.name) && this.vdb.equals(other.vdb);
+    	}
+    }
+    
+    private static class MatTableEntry implements Serializable {
+		private static final long serialVersionUID = 8559613701442751579L;
+    	long lastUpdate = System.currentTimeMillis();
+    	boolean valid;
+    }
+    
+    private Cache<MatTableKey, MatTableEntry> tables;
+    private SessionAwareCache<CachedResults> distributedCache;
+
+    public TempTableDataManager(ProcessorDataManager processorDataManager, BufferManager bufferManager, 
+    		Executor executor, SessionAwareCache<CachedResults> cache, SessionAwareCache<CachedResults> distibutedCache, CacheFactory cacheFactory){
+        this.processorDataManager = processorDataManager;
+        this.bufferManager = bufferManager;
+        this.executor = executor;
+        this.cache = cache;
+        this.distributedCache = distibutedCache;
+        if (distibutedCache != null) {
+	        CacheConfiguration cc = new CacheConfiguration(Policy.LRU, -1, -1);
+	        tables = cacheFactory.get(Cache.Type.MATTABLES, cc);
+        }
+    }
+    
+	public TupleSource registerRequest(
+		CommandContext context,
+		Command command,
+		String modelName,
+		String connectorBindingId, int nodeID)
+		throws TeiidComponentException, TeiidProcessingException {          
+
+		TempTableStore tempTableStore = context.getTempTableStore();
+        if(tempTableStore != null) {
+            TupleSource result = registerRequest(context, modelName, command);
+            if (result != null) {
+            	return result;
+            }
+        }
+        return this.processorDataManager.registerRequest(context, command, modelName, connectorBindingId, nodeID);
+	}
+	        
+    TupleSource registerRequest(CommandContext context, String modelName, Command command) throws TeiidComponentException, TeiidProcessingException {
+    	TempTableStore contextStore = context.getTempTableStore();
+        if (command instanceof Query) {
+            Query query = (Query)command;
+            return registerQuery(context, contextStore, query);
+        }
+        if (command instanceof ProcedureContainer) {
+        	if (command instanceof StoredProcedure) {
+        		StoredProcedure proc = (StoredProcedure)command;
+        		if (CoreConstants.SYSTEM_ADMIN_MODEL.equals(modelName)) {
+	        		TupleSource result = handleSystemProcedures(context, proc);
+	        		if (result != null) {
+	        			return result;
+	        		}
+        		} else if (proc.getGroup().isGlobalTable()) {
+        			return handleCachedProcedure(context, proc);
+        		}
+        		return null; //it's not a stored procedure we want to handle
+        	}
+        	
+        	GroupSymbol group = ((ProcedureContainer)command).getGroup();
+        	if (!group.isTempGroupSymbol()) {
+        		return null;
+        	}
+        	final String groupKey = group.getNonCorrelationName().toUpperCase();
+            final TempTable table = contextStore.getOrCreateTempTable(groupKey, command, bufferManager, false);
+        	if (command instanceof Insert) {
+        		Insert insert = (Insert)command;
+        		TupleSource ts = insert.getTupleSource();
+        		if (ts == null) {
+        			List<Object> values = new ArrayList<Object>(insert.getValues().size());
+        			for (Expression expr : (List<Expression>)insert.getValues()) {
+        				values.add(Evaluator.evaluate(expr));
+					}
+        			ts = new CollectionTupleSource(Arrays.asList(values).iterator());
+        		}
+        		return table.insert(ts, insert.getVariables());
+        	}
+        	if (command instanceof Update) {
+        		final Update update = (Update)command;
+        		final Criteria crit = update.getCriteria();
+        		return table.update(crit, update.getChangeList());
+        	}
+        	if (command instanceof Delete) {
+        		final Delete delete = (Delete)command;
+        		final Criteria crit = delete.getCriteria();
+        		if (crit == null) {
+        			//because we are non-transactional, just use a truncate
+        			int rows = table.truncate();
+                    return CollectionTupleSource.createUpdateCountTupleSource(rows);
+        		}
+        		return table.delete(crit);
+        	}
+        }
+    	if (command instanceof Create) {
+    		Create create = (Create)command;
+    		String tempTableName = create.getTable().getCanonicalName();
+    		if (contextStore.hasTempTable(tempTableName)) {
+                throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableStore.table_exist_error", tempTableName));//$NON-NLS-1$
+            }
+    		contextStore.addTempTable(tempTableName, create, bufferManager, true);
+            return CollectionTupleSource.createUpdateCountTupleSource(0);	
+    	}
+    	if (command instanceof Drop) {
+    		String tempTableName = ((Drop)command).getTable().getCanonicalName();
+    		contextStore.removeTempTableByName(tempTableName);
+            return CollectionTupleSource.createUpdateCountTupleSource(0);
+    	}
+        return null;
+    }
+
+	private TupleSource handleCachedProcedure(CommandContext context,
+			StoredProcedure proc) throws TeiidComponentException,
+			QueryMetadataException, TeiidProcessingException {
+		String fullName = context.getMetadata().getFullName(proc.getProcedureID());
+		LogManager.logDetail(LogConstants.CTX_DQP, "processing cached procedure request for", fullName); //$NON-NLS-1$
+		LinkedList<Object> vals = new LinkedList<Object>();
+		for (SPParameter param : proc.getInputParameters()) {
+			vals.add(((Constant)param.getExpression()).getValue());
+		}
+		//collapse the hash to single byte for the key to restrict the possible results to 256
+		int hash = vals.hashCode();
+		hash |= (hash >>> 16);
+		hash |= (hash >>> 8);
+		hash &= 0x000000ff;
+		CacheID cid = new CacheID(new ParseInfo(), fullName + hash, context.getVdbName(), 
+				context.getVdbVersion(), context.getConnectionID(), context.getUserName());
+		cid.setParameters(vals);
+		CachedResults results = cache.get(cid);
+		if (results != null) {
+			TupleBuffer buffer = results.getResults();
+			return buffer.createIndexedTupleSource();
+		}
+		//construct a query with a no cache hint
+		//note that it's safe to use the stringified form of the parameters because
+		//it's not possible to use xml/clob/blob/object
+		CacheHint hint = proc.getCacheHint();
+		proc.setCacheHint(null);
+		Option option = new Option();
+		option.setNoCache(true);
+		option.addNoCacheGroup(fullName);
+		proc.setOption(option);
+		int determinismLevel = context.resetDeterminismLevel();
+		QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(proc.toString(), fullName.toUpperCase(), context);
+		qp.setNonBlocking(true);
+		BatchCollector bc = qp.createBatchCollector();
+		TupleBuffer tb = bc.collectTuples();
+		CachedResults cr = new CachedResults();
+		cr.setResults(tb);
+		cr.setHint(hint);
+		cache.put(cid, context.getDeterminismLevel(), cr, hint != null?hint.getTtl():null);
+		context.setDeterminismLevel(determinismLevel);
+		return tb.createIndexedTupleSource();
+	}
+
+	private TupleSource handleSystemProcedures(CommandContext context, StoredProcedure proc)
+			throws TeiidComponentException, QueryMetadataException,
+			QueryProcessingException, QueryResolverException,
+			QueryValidatorException, TeiidProcessingException,
+			ExpressionEvaluationException {
+		QueryMetadataInterface metadata = context.getMetadata();
+		TempTableStore globalStore = context.getGlobalTableStore();
+		if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEW)) {
+			Object groupID = validateMatView(metadata, proc);
+			String matViewName = metadata.getFullName(groupID);
+			String matTableName = RelationalPlanner.MAT_PREFIX+matViewName.toUpperCase();
+			LogManager.logDetail(LogConstants.CTX_MATVIEWS, "processing refreshmatview for", matViewName); //$NON-NLS-1$
+			MatTableInfo info = globalStore.getMatTableInfo(matTableName);
+			boolean invalidate = Boolean.TRUE.equals(((Constant)proc.getParameter(1).getExpression()).getValue());
+			if (invalidate) {
+				touchTable(context, matTableName, false);
+			}
+			MatState oldState = info.setState(MatState.NEEDS_LOADING, invalidate?Boolean.FALSE:null, null);
+			if (oldState == MatState.LOADING) {
+				return CollectionTupleSource.createUpdateCountTupleSource(-1);
+			}
+			GroupSymbol group = new GroupSymbol(matViewName);
+			group.setMetadataID(groupID);
+			Object matTableId = RelationalPlanner.getGlobalTempTableMetadataId(group, matTableName, context, metadata, AnalysisRecord.createNonRecordingRecord());
+			GroupSymbol matTable = new GroupSymbol(matTableName);
+			matTable.setMetadataID(matTableId);
+			int rowCount = loadGlobalTable(context, matTable, matTableName, globalStore, info, null);
+			return CollectionTupleSource.createUpdateCountTupleSource(rowCount);
+		} else if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEWROW)) {
+			Object groupID = validateMatView(metadata, proc);
+			Object pk = metadata.getPrimaryKey(groupID);
+			String matViewName = metadata.getFullName(groupID);
+			if (pk == null) {
+				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_pk", matViewName)); //$NON-NLS-1$
+			}
+			List<?> ids = metadata.getElementIDsInKey(pk);
+			if (ids.size() > 1) {
+				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_composite", matViewName)); //$NON-NLS-1$
+			}
+			String matTableName = RelationalPlanner.MAT_PREFIX+matViewName.toUpperCase();
+			MatTableInfo info = globalStore.getMatTableInfo(matTableName);
+			if (!info.isValid()) {
+				return CollectionTupleSource.createUpdateCountTupleSource(-1);
+			}
+			TempTable tempTable = globalStore.getOrCreateTempTable(matTableName, new Query(), bufferManager, false);
+			if (!tempTable.isUpdatable()) {
+				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_updatable", matViewName)); //$NON-NLS-1$
+			}
+			Constant key = (Constant)proc.getParameter(2).getExpression();
+			LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.row_refresh", matViewName, key)); //$NON-NLS-1$
+			String queryString = Reserved.SELECT + " * " + Reserved.FROM + ' ' + matViewName + ' ' + Reserved.WHERE + ' ' + //$NON-NLS-1$
+				metadata.getFullName(ids.iterator().next()) + " = ?" + ' ' + Reserved.OPTION + ' ' + Reserved.NOCACHE; //$NON-NLS-1$
+			QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(queryString, matViewName.toUpperCase(), context, key.getValue());
+			qp.setNonBlocking(true);
+			TupleSource ts = new BatchCollector.BatchProducerTupleSource(qp);
+			tempTable = globalStore.getOrCreateTempTable(matTableName, new Query(), bufferManager, false);
+			List<?> tuple = ts.nextTuple();
+			boolean delete = false;
+			if (tuple == null) {
+				delete = true;
+				tuple = Arrays.asList(key.getValue());
+			}
+			List<?> result = tempTable.updateTuple(tuple, delete);
+			//TODO: maintain a table log and distribute the events
+			return CollectionTupleSource.createUpdateCountTupleSource(result != null ? 1 : 0);
+		}
+		return null;
+	}
+
+	private Object validateMatView(QueryMetadataInterface metadata,
+			StoredProcedure proc) throws TeiidComponentException,
+			TeiidProcessingException {
+		String name = (String)((Constant)proc.getParameter(1).getExpression()).getValue();
+		try {
+			Object groupID = metadata.getGroupID(name);
+			if (!metadata.hasMaterialization(groupID) || metadata.getMaterialization(groupID) != null) {
+				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.not_implicit_matview", name)); //$NON-NLS-1$
+			}
+			return groupID;
+		} catch (QueryMetadataException e) {
+			throw new TeiidProcessingException(e);
+		}
+	}
+
+	private TupleSource registerQuery(final CommandContext context,
+			TempTableStore contextStore, Query query)
+			throws TeiidComponentException, QueryMetadataException,
+			TeiidProcessingException, ExpressionEvaluationException,
+			QueryProcessingException {
+		final GroupSymbol group = query.getFrom().getGroups().get(0);
+		if (!group.isTempGroupSymbol()) {
+			return null;
+		}
+		final String tableName = group.getNonCorrelationName().toUpperCase();
+		boolean remapColumns = !tableName.equalsIgnoreCase(group.getName());
+		TempTable table = null;
+		if (group.isGlobalTable()) {
+			final TempTableStore globalStore = context.getGlobalTableStore();
+			final MatTableInfo info = globalStore.getMatTableInfo(tableName);
+			Long loadTime = null;
+			if (this.distributedCache != null) {
+				MatTableKey key = new MatTableKey();
+				key.name = tableName;
+				key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
+				
+				MatTableEntry entry = this.tables.get(key);
+				if (entry != null && entry.lastUpdate > info.getUpdateTime() 
+						&& info.getState() != MatState.LOADING) {
+					//remote load
+					info.setState(MatState.NEEDS_LOADING, entry.valid, null);
+					loadTime = entry.lastUpdate;
+				}
+			}
+			boolean load = info.shouldLoad();
+			if (load) {
+				if (!info.isValid()) {
+					//blocking load
+					loadGlobalTable(context, group, tableName, globalStore, info, loadTime);
+				} else {
+					loadAsynch(context, group, tableName, globalStore, info, loadTime);
+				}
+			} 
+			table = globalStore.getOrCreateTempTable(tableName, query, bufferManager, false);
+		} else {
+			table = contextStore.getOrCreateTempTable(tableName, query, bufferManager, true);
+		}
+		if (remapColumns) {
+			//convert to the actual table symbols (this is typically handled by the languagebridgefactory
+			ExpressionMappingVisitor emv = new ExpressionMappingVisitor(null) {
+				@Override
+				public Expression replaceExpression(Expression element) {
+					if (element instanceof ElementSymbol) {
+						ElementSymbol es = (ElementSymbol)element;
+						((ElementSymbol) element).setName(tableName + ElementSymbol.SEPARATOR + es.getShortName());
+					}
+					return element;
+				}
+			};
+			PostOrderNavigator.doVisit(query, emv);
+		}
+		return table.createTupleSource(query.getProjectedSymbols(), query.getCriteria(), query.getOrderBy());
+	}
+
+	private void loadAsynch(final CommandContext context,
+			final GroupSymbol group, final String tableName,
+			final TempTableStore globalStore, final MatTableInfo info,
+			final Long loadTime) {
+		Callable<Integer> toCall = new Callable<Integer>() {
+			@Override
+			public Integer call() throws Exception {
+				return loadGlobalTable(context, group, tableName, globalStore, info, loadTime);
+			}
+		};
+		FutureTask<Integer> task = new FutureTask<Integer>(toCall);
+		executor.execute(task);
+	}
+
+	private int loadGlobalTable(CommandContext context,
+			GroupSymbol group, final String tableName,
+			TempTableStore globalStore, MatTableInfo info, Long loadTime)
+			throws TeiidComponentException, TeiidProcessingException {
+		LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.loading", tableName)); //$NON-NLS-1$
+		QueryMetadataInterface metadata = context.getMetadata();
+		Create create = new Create();
+		create.setTable(group);
+		List<ElementSymbol> allColumns = ResolverUtil.resolveElementsInGroup(group, metadata); 
+		create.setColumns(allColumns);
+		Object pk = metadata.getPrimaryKey(group.getMetadataID());
+		if (pk != null) {
+			List<ElementSymbol> pkColumns = resolveIndex(metadata, allColumns, pk);
+			create.getPrimaryKey().addAll(pkColumns);
+		}
+		TempTable table = globalStore.addTempTable(tableName, create, bufferManager, false);
+		table.setUpdatable(false);
+		CacheHint hint = table.getCacheHint();
+		boolean updatable = false;
+		if (hint != null) {
+			table.setPreferMemory(hint.getPrefersMemory());
+			if (hint.getTtl() != null) {
+				info.setTtl(table.getCacheHint().getTtl());
+			}
+			if (pk != null) {
+				updatable = hint.isUpdatable();
+			}
+		}
+		int rowCount = -1;
+		try {
+			String fullName = metadata.getFullName(group.getMetadataID());
+			TupleSource ts = null;
+			CacheID cid = null;
+			if (distributedCache != null) {
+				cid = new CacheID(new ParseInfo(), fullName, context.getVdbName(), 
+						context.getVdbVersion(), context.getConnectionID(), context.getUserName());
+				CachedResults cr = this.distributedCache.get(cid);
+				if (cr != null) {
+					ts = cr.getResults().createIndexedTupleSource();
+				}
+			}
+			
+			List<ElementSymbol> variables = table.getColumns();
+			
+			if (ts == null) {
+				variables = allColumns;
+				//TODO: coordinate a distributed load
+				//TODO: order by primary key nulls first - then have an insert ordered optimization
+				String transformation = metadata.getVirtualPlan(group.getMetadataID()).getQuery();
+				QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(transformation, fullName, context);
+				qp.setNonBlocking(true);
+				
+				if (distributedCache != null) {
+					CachedResults cr = new CachedResults();
+					BatchCollector bc = qp.createBatchCollector();
+					TupleBuffer tb = bc.collectTuples();
+					cr.setResults(tb);
+					touchTable(context, fullName, true);
+					this.distributedCache.put(cid, FunctionMethod.VDB_DETERMINISTIC, cr, info.getTtl());
+					ts = tb.createIndexedTupleSource();
+				} else {
+					ts = new BatchCollector.BatchProducerTupleSource(qp);
+				}
+			}
+			
+			//TODO: if this insert fails, it's unnecessary to do the undo processing
+			table.insert(ts, variables);
+			rowCount = table.getRowCount();
+			//TODO: could pre-process indexes to remove overlap
+			for (Object index : metadata.getIndexesInGroup(group.getMetadataID())) {
+				List<ElementSymbol> columns = resolveIndex(metadata, allColumns, index);
+				table.addIndex(columns);
+			}
+			for (Object key : metadata.getUniqueKeysInGroup(group.getMetadataID())) {
+				List<ElementSymbol> columns = resolveIndex(metadata, allColumns, key);
+				table.addIndex(columns);
+			}
+			table.setUpdatable(updatable);
+		} catch (TeiidComponentException e) {
+			LogManager.logError(LogConstants.CTX_MATVIEWS, e, QueryPlugin.Util.getString("TempTableDataManager.failed_load", tableName)); //$NON-NLS-1$
+			throw e;
+		} catch (TeiidProcessingException e) {
+			LogManager.logError(LogConstants.CTX_MATVIEWS, e, QueryPlugin.Util.getString("TempTableDataManager.failed_load", tableName)); //$NON-NLS-1$
+			throw e;
+		} finally {
+			if (rowCount == -1) {
+				info.setState(MatState.FAILED_LOAD, null, null);
+			} else {
+				globalStore.swapTempTable(tableName, table);
+				info.setState(MatState.LOADED, true, loadTime);
+				LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.loaded", tableName, rowCount)); //$NON-NLS-1$
+			}
+		}
+		return rowCount;
+	}
+
+	private void touchTable(CommandContext context, String fullName, boolean valid) {
+		MatTableKey key = new MatTableKey();
+		key.name = fullName;
+		key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
+		MatTableEntry matTableEntry = new MatTableEntry();
+		matTableEntry.valid = valid;
+		tables.put(key, matTableEntry, null);
+	}
+
+	/**
+	 * Return a list of ElementSymbols for the given index/key object
+	 */
+	private List<ElementSymbol> resolveIndex(QueryMetadataInterface metadata,
+			List<ElementSymbol> allColumns, Object pk)
+			throws TeiidComponentException, QueryMetadataException {
+		Collection<?> pkIds = metadata.getElementIDsInKey(pk);
+		List<ElementSymbol> pkColumns = new ArrayList<ElementSymbol>(pkIds.size());
+		for (Object col : pkIds) {
+			pkColumns.add(allColumns.get(metadata.getPosition(col)-1));
+		}
+		return pkColumns;
+	}
+
+	public Object lookupCodeValue(CommandContext context, String codeTableName,
+			String returnElementName, String keyElementName, Object keyValue)
+			throws BlockedException, TeiidComponentException,
+			TeiidProcessingException {
+    	String matTableName = CODE_PREFIX + (codeTableName + ElementSymbol.SEPARATOR + keyElementName + ElementSymbol.SEPARATOR + returnElementName).toUpperCase(); 
+
+    	ElementSymbol keyElement = new ElementSymbol(matTableName + ElementSymbol.SEPARATOR + keyElementName);
+    	ElementSymbol returnElement = new ElementSymbol(matTableName + ElementSymbol.SEPARATOR + returnElementName);
+    	
+    	QueryMetadataInterface metadata = context.getMetadata();
+    	
+    	keyElement.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(metadata.getElementID(codeTableName + ElementSymbol.SEPARATOR + keyElementName))));
+    	returnElement.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(metadata.getElementID(codeTableName + ElementSymbol.SEPARATOR + returnElementName))));
+    	
+    	TempMetadataID id = context.getGlobalTableStore().getMetadataStore().getTempGroupID(matTableName);
+    	if (id == null) {
+	    	id = context.getGlobalTableStore().getMetadataStore().addTempGroup(matTableName, Arrays.asList(keyElement, returnElement), false, true);
+	    	String queryString = Reserved.SELECT + ' ' + keyElementName + " ," + returnElementName + ' ' + Reserved.FROM + ' ' + codeTableName; //$NON-NLS-1$ 
+	    	id.setQueryNode(new QueryNode(matTableName, queryString));
+	    	id.setPrimaryKey(id.getElements().subList(0, 1));
+	    	CacheHint hint = new CacheHint(true, null);
+	    	id.setCacheHint(hint);
+    	}
+    	Query query = RelationalPlanner.createMatViewQuery(id, matTableName, Arrays.asList(returnElement), true);
+    	query.setCriteria(new CompareCriteria(keyElement, CompareCriteria.EQ, new Constant(keyValue)));
+    	
+    	TupleSource ts = registerQuery(context, context.getTempTableStore(), query);
+    	List<?> row = ts.nextTuple();
+    	Object result = null;
+    	if (row != null) {
+    		result = row.get(0);
+    	}
+    	ts.closeSource();
+    	return result;
+    }
+
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/main/resources/org/teiid/query/i18n.properties
===================================================================
--- branches/7.2.x/engine/src/main/resources/org/teiid/query/i18n.properties	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/resources/org/teiid/query/i18n.properties	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,884 +0,0 @@
-#
-# JBoss, Home of Professional Open Source.
-# See the COPYRIGHT.txt file distributed with this work for information
-# regarding copyright ownership.  Some portions may be licensed
-# to Red Hat, Inc. under one or more contributor license agreements.
-# 
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-# 
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-# Lesser General Public License for more details.
-# 
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-# 02110-1301 USA.
-#
-
-# Error messages for query (015) project to address internationalization
-# Format:
-#
-
-# function (001)
-ERR.015.001.0002 = Cannot find implementation for known function {0}
-ERR.015.001.0003 = Error while evaluating function {0}
-ERR.015.001.0004 = Unable to access function implementation for [{0}]
-ERR.015.001.0005 = ERROR loading system functions: {0}
-ERR.015.001.0017 = Left count is invalid: {0}
-ERR.015.001.0025 = Pad length must be > 0.
-ERR.015.001.0027 = Pad string for lpad/rpad must have length greater than 0.
-ERR.015.001.0031 = Source and destination character lists must be the same length.
-ERR.015.001.0033 = Error converting [{0}] of type {1} to type {2}
-ERR.015.001.0035 = The context function may only be used in XML queries.
-ERR.015.001.0035a = The rowlimit and rowlimitexception functions may only be used in XML queries.
-ERR.015.001.0042 = Illegal argument for formating: {0}
-ERR.015.001.0043 = Parse Exception occurs for executing: {0} {1}
-ERR.015.001.0044 = Function metadata source is of invalid type: {0}
-ERR.015.001.0045 = Function method is of invalid type: {0}
-ERR.015.001.0046 = The function "{0}" will not be added because a function with the same name and signature already exists.
-ERR.015.001.0047 = Unexpected exception while loading "{1}.{2}" for UDF "{0}"
-FunctionTree.not_void = UDF "{0}" method "{1}" must not return void.
-FunctionTree.not_public = UDF "{0}" method "{1}" must be public.
-FunctionTree.not_static = UDF "{0}" method "{1}" must be static.
-FunctionTree.no_class = Could not load UDF "{0}", since its invocation class "{1}" could not be found.
-FunctionTree.no_method = UDF "{0}" could not loaded, since no method on class "{1}" with name "{2}" has a matching type signature.
-ERR.015.001.0048 = Unable to represent average value from {0} / {1}
-ERR.015.001.0050 = Unable to compute aggregate function {0} on data of type {1}
-ERR.015.001.0052 = {0} must be non-null.
-ERR.015.001.0053 = Method parameter must be non-null.
-ERR.015.001.0054 = Type is unknown: {0}
-ERR.015.001.0055 = {0} exceeds maximum length of {1}
-ERR.015.001.0056 = {0} has invalid first character: {1}
-ERR.015.001.0057 = {0} has invalid character: {1}
-ERR.015.001.0058 = {0} cannot end with a ''.''
-ERR.015.001.0061 = <start> value of {0} is invalid, which should never be less than zero or bigger than the length of original string {1}
-ERR.015.001.0062 = <length> value of {0} is invalid, which should never less be than zero.
-ERR.015.001.0063 = Input String is an empty string but start value or/and length value is bigger than zero.
-ERR.015.001.0066 = Unknown type signature for evaluating function of: {0} ({1})
-ERR.015.001.0069 = Unknown type signature for evaluating function of: {0} ({1})
-
-# mapping (002)
-ERR.015.002.0009 = Search direction arg ''{0}'' is not one of the search constants defined in MappingNodeConstants.
-ERR.015.002.0010 = Value for property ''{0}'' is null.
-ERR.015.002.0011 = Invalid type: {0}
-
-
-# parser (005)
-QueryParser.emptysql=Parser cannot parse an empty sql statement.
-QueryParser.parsingError=Parsing error: {0}
-QueryParser.nullSqlCrit=Parser cannot parse a null sql criteria.
-QueryParser.lexicalError= Lexical error: {0}
-QueryParser.nullSqlExpr= Parser cannot parse a null sql expression.
-QueryParser.xqueryCompilation= Direct usage of XQuery is no longer supported, use XMLQUERY instead.
-
-# processor (006)
-ERR.015.006.0010= Unknown criteria type: {0}
-ERR.015.006.0011= Unable to evaluate {0} expression of {1}
-ERR.015.006.0012= Unknown compare criteria operator: {0}
-ERR.015.006.0014= Failed to create regular expression from match pattern: {0}. {1}
-ERR.015.006.0015= Unable to evaluate expression of {0}
-ERR.015.006.0016= Unknown expression type: {0}
-ERR.015.006.0033= Unable to evaluate {0}: {1}
-ERR.015.006.0055= Unable to evaluate LOOKUP function.
-ERR.015.006.0057= Unknown subquery comparison predicate quantifier: {0}
-ERR.015.006.0058= The command of this scalar subquery returned more than one value: {0}
-
-# report (007)
-ERR.015.007.0001= Item may not be null
-
-# resolver (008)
-ERR.015.008.0003= Only one XML document may be specified in the FROM clause of a query.
-ERR.015.008.0007= Incorrect number of parameters specified on the stored procedure {2} - expected {0} but got {1}
-ERR.015.008.0009= {1} is not allowed on the virtual group {0}: no {1} procedure was defined.
-ERR.015.008.0010= INSERT statement must have the same number of elements and values specified.  This statement has {0} elements and {1} values.
-ERR.015.008.0011= Error parsing query plan transformation for {0}
-ERR.015.008.0012= Unable to resolve update procedure as the virtual group context is ambiguous.
-ERR.015.008.0013= Error parsing query plan transformation for {0}
-ERR.015.008.0015= Unknown statement type: {0}
-ERR.015.008.0019= Unable to resolve element: {0}
-ERR.015.008.0020= Element is ambiguous and must be qualified: {0}
-ERR.015.008.0022= Failed parsing reference binding: {0}
-ERR.015.008.0025= Binding reference cannot be a function: {0}
-ERR.015.008.0026= Expression ''{0}'' has a parameter with non-determinable type information.  The use of an explicit convert may be necessary.
-ERR.015.008.0027= The expressions in this criteria are being compared but are of differing types ({0} and {1}) and no implicit conversion is available:  {2}
-ERR.015.008.0029= This criteria must have string or CLOB expressions on each side: {0}
-ERR.015.008.0030= Type cannot be null for expression: {0}
-ERR.015.008.0031= This criteria must have values only of the same type as the left expression: {0}
-ERR.015.008.0032= There must be exactly one projected symbol of the subquery: {0}
-ERR.015.008.0033= The left expression must have a type convertible to the type of the subquery projected symbol: {0}
-ERR.015.008.0035= Type was null for {0} in function {1}
-ERR.015.008.0036= The function ''{0}'' has more than one possible signature.
-ERR.015.008.0037= The conversion from {0} to {1} is not allowed.
-ERR.015.008.0039= The function ''{0}'' is an unknown form.  Check that the function name and number of arguments is correct.
-ERR.015.008.0040= The function ''{0}'' is a valid function form, but the arguments do not match a known type signature and cannot be converted using implicit type conversions.
-ERR.015.008.0041= Expected value of type ''{0}'' but ''{1}'' is of type ''{2}'' and no implicit conversion is available.
-ERR.015.008.0042= Element ''{0}'' in ORDER BY is ambiguous and may refer to more than one element of SELECT clause.
-ERR.015.008.0043= Element ''{0}'' in ORDER BY was not found in SELECT clause.
-ERR.015.008.0045= Failed parsing insert plan for {0}
-ERR.015.008.0046= The symbol {0} may only be used once in the FROM clause.
-ERR.015.008.0047= The symbol {0} refers to a group not defined in the FROM clause.
-ERR.015.008.0049= Bindings must be specified
-ERR.015.008.0051= Symbol {0} is specified with an unknown group context
-ERR.015.008.0053= Element "{0}" is ambiguous, it exists in two or more groups.
-ERR.015.008.0054= Element "{0}" is not defined by any relevant group.
-ERR.015.008.0055= Group specified is ambiguous, resubmit the query by fully qualifying the group name
-ambiguous_procedure= Procedure ''{0}'' is ambiguous, use the fully qualified name instead
-ERR.015.008.0056= Group does not exist
-ERR.015.008.0061= Unable to resolve stored procedure {0} the datatype for the parameter {1} is not specified.
-ERR.015.008.0062= Unable to resolve return element referred to by LOOKUP function: {0}
-ERR.015.008.0063= The first three arguments for the LOOKUP function must be specified as constants.
-ERR.015.008.0065= Group {0} is not allowed in LOOKUP function.
-ERR.015.008.0068= Could not find a common type to which all {0} expressions can be implicitly converted: {1}
-ERR.015.008.0070= Aliased Select Symbols are not valid in XML Queries.
-XMLQueryResolver.no_expressions_in_select=Expressions cannot be selected by XML Queries
-
-# sql (010)
-ERR.015.010.0001= Invalid compare operator: {0}
-ERR.015.010.0002= Invalid logical operator: {0}
-ERR.015.010.0003= Cannot set null collection of elements on GroupBy
-ERR.015.010.0006= Invalid parameter type [{0}] must be IN, OUT, INOUT, RETURN_VALUE, RESULT_SET
-ERR.015.010.0009= No columns exist.
-ERR.015.010.0010= Invalid column index: {0}
-ERR.015.010.0011= Parameter cannot be null
-ERR.015.010.0014= Constant type should never be null
-ERR.015.010.0015= Unknown constant type: {0}
-ERR.015.010.0016= A group symbol may not resolve to a null metadata ID.
-ERR.015.010.0017= The name of a symbol may not be null.
-ERR.015.010.0018= Inconsistent number of elements in transformation projected symbols and virtual group.
-ERR.015.010.0021= Elements cannot be null
-ERR.015.010.0022= Functions cannot be null
-ERR.015.010.0023= Groups cannot be null
-ERR.015.010.0029= Cannot create AliasSymbol wrapping AliasSymbol
-ERR.015.010.0031= Illegal variable name ''{1}''.  Variable names can only be prefixed with the special group name ''{0}''.
-ERR.015.010.0032= Variable {0} was previously declared.
-ERR.015.010.0035= The <expression> cannot be null in CASE <expression>
-ERR.015.010.0036= There must be at least one WHEN expression and one THEN expression. The number of WHEN and THEN expressions must be equal.
-ERR.015.010.0037= The WHEN part of the CASE expression must contain an expression.
-ERR.015.010.0038= The THEN part of the CASE expression must contain an expression
-ERR.015.010.0039= The WHEN part of the searched CASE expression must contain a criteria.
-
-# util (011)
-
-# validator (012)
-ERR.015.012.0001 = The query defining an updatable virtual group cannot be a UNION query
-ERR.015.012.0002 = The query defining an updatable virtual group cannot be a stored query or stored procedure execution
-ERR.015.012.0003 = The query defining an updatable virtual group cannot be an INSERT
-ERR.015.012.0004 = The query defining an updatable virtual group cannot be an UPDATE
-ERR.015.012.0005 = The query defining an updatable virtual group cannot be a DELETE
-ERR.015.012.0006 = The query defining an updatable virtual group should not use GROUP BY or HAVING.
-ERR.015.012.0007 = The query defining an updatable virtual group cannot use a non-constant, non-column reference expressions in its SELECT clause {0}.
-ERR.015.012.0009 = The query defining an updatable virtual group cannot have more than one group in its FROM clause {0}
-ERR.015.012.0010 = The query defining an updatable simple virtual group should select all the required elements in its FROM clause {0}
-ERR.015.012.0011 = There must be exactly one projected symbol in the subcommand of an IN clause.
-ERR.015.012.0012 = An AssignmentStatement cannot change the value of a {0} or {1} variable.
-ERR.015.012.0016 = Variable {0} not assigned any value in this procedure.
-ERR.015.012.0017 = Variables declared the procedure''s DeclareStatement cannot be one of the special variables: {0}, {1} and {2}.
-ERR.015.012.0019 = TranslateCriteria cannot be used in on an if or while statement.
-ERR.015.012.0020 = Elements used on the criteria of an if or while statement should be variables declared in the procedure, virtual group elements can be used in the HAS Criteria
-ERR.015.012.0021 = Element being translated in the WITH clause not among the elements on the ON clause of the TranslateCriteria.
-ERR.015.012.0022 = Unable to translate criteria on the update command against the virtual group, the element {0} is mapped to an aggregate symbol in the virtual group''s query transform, and cannot be translated.
-ERR.015.012.0023 = Unable to translate criteria on the update command against the virtual group, the element {0} is mapped to an expression whose elements are not present on the command in the procedure using the translated criteria.
-ERR.015.012.0024 = The following data elements are not supported in the SELECT clause: {0}.
-ERR.015.012.0025 = Command must project at least one symbol
-ERR.015.012.0026 = Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in SELECT DISTINCT, ORDER BY, GROUP BY, KEYS, or non-all set queries: [{0}]
-ERR.015.012.0027 = Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in comparison: {0}.
-ValidationVisitor.expression_requires_name = Non-column expressions require a name in XMLATTRIBUTES, XMLFOREST, QUERYSTRING, or TEXTAGG with HEADER
-ValidationVisitor.invalid_lookup_key=Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used as LOOKUP key columns: {0}.
-ValidationVisitor.limit_not_valid_for_xml=The limit clause cannot be used on an XML document query.
-ValidationVisitor.translated_or=Translated user criteria must not contain OR criteria
-ValidationVisitor.union_insert = Select into is not allowed under a set operation: {0}.
-ValidationVisitor.multisource_insert = A multi-source table, {0}, cannot be used in an INSERT with query expression or SELECT INTO statement.
-ValidationVisitor.virtual_update_subquery = Subqueries are not allowed in the criteria for a virtual UPDATE/DELETE: {0}
-ValidationVisitor.invalid_encoding = Invalid encoding: {0}.
-ERR.015.012.0029 = INSERT, UPDATE, and DELETE not allowed on XML documents
-ERR.015.012.0030 = Commands used in stored procedure language not allowed on XML documents
-ERR.015.012.0031 = Queries against XML documents can not have a GROUP By clause
-ERR.015.012.0032 = Queries against XML documents can not have a HAVING clause
-ERR.015.012.0033 = Metadata does not allow updates on the group: {0}
-ERR.015.012.0034 = Queries involving UNIONs, INTERSECTs and EXCEPTs not allowed on XML documents
-ERR.015.012.0035 = Queries combined with the set operator {0} must have the same number of output elements.
-ERR.015.012.0037 = Invalid symbol: {0}. When an aggregate function is used in the SELECT clause and no GROUP BY clause is specified, the SELECT clause may contain only aggregate functions and constants.
-ERR.015.012.0038 = Invalid symbol: {0}. When a GROUP BY clause is used, all elements in the SELECT clause must be declared in the GROUP BY clause.
-ERR.015.012.0039 = Nested aggregate expressions are not allowed: {0}
-ERR.015.012.0041 = The aggregate function {0} cannot be used with non-numeric expressions: {1}
-AggregateValidationVisitor.non_comparable = The aggregate function {0} cannot be used with non-comparable expressions: {1}
-AggregateValidationVisitor.non_xml = The XMLAGG aggregate function {0} requires an expression of type XML: {1}
-AggregateValidationVisitor.non_boolean=The boolean aggregate functions ANY, SOME, EVERY require a boolean expression.
-AggregateValidationVisitor.invalid_distinct=The enhanced numeric aggregate functions STDDEV_POP, STDDEV_SAMP, VAR_POP, VAR_SAMP cannot have DISTINCT specified.
-ERR.015.012.0052 = The element [{0}] is in an INSERT but does not support updates.
-ERR.015.012.0053 = Element in the group {0}, for which value is not specified in the insert command is neither nullable nor has a default value: {1}
-ERR.015.012.0054 = Column variables do not reference columns on group "{0}": {1}
-ERR.015.012.0055 = Element {0} does not allow nulls.
-ERR.015.012.0058 = Left side of update expression may not be a variable or a reference to an external element: {0}
-ERR.015.012.0059 = Left side of update expression must be an element that supports update: {0}
-ERR.015.012.0060 = Element {0} does not allow nulls.
-ERR.015.012.0061 = Update values must be a constant expression.  The expression ''{0}'' cannot be evaluated to a constant.
-ERR.015.012.0062 = Elements cannot appear more than once in a SET or USING clause.  The following elements are duplicated: {0}
-ERR.015.012.0063 = Multiple failures occurred during validation:
-ERR.015.012.0064 = Validation succeeded
-ERR.015.012.0065 = Nested Loop can not use the same cursor name as that of its parent.
-ERR.015.012.0067 = No scalar subqueries are allowed in the SELECT with no FROM clause.
-ERR.015.012.0069 = INTO clause can not be used in XML query.
-
-# optimizer (004)
-ERR.015.004.0007= Can''t convert plan node of type {0}
-ERR.015.004.0009= Error finding connectorBindingID for command
-ERR.015.004.0010= Unknown group specified in OPTION MAKEDEP/MAKENOTDEP: {0}
-ERR.015.004.0012= Group has an access pattern which has not been met: group(s) {0}; access pattern(s) {1}
-ERR.015.004.0020= Error getting model for {0}
-ERR.015.004.0023= Error rewriting criteria: {0}
-ERR.015.004.0024= Unable to create a query plan that sends a criteria to \"{0}\".  This connection factory requires criteria set to true indicating that a query against this model requires criteria.  
-ERR.015.004.0029= Could not resolve group symbol {0}
-ERR.015.004.0035= The criteria {0} has elements from the root staging table and the document nodes which is not allowed.
-ERR.015.004.0037= No mapping node found named, ''{0}', in use of ''context''
-ERR.015.004.0046= The XML document element(s) {0} are not mapped to data and cannot be used in the criteria \"{1}\".
-ERR.015.004.0054= Could not parse query transformation for {0}: {1}
-ERR.015.004.0068= Context functions within the same conjunct refer to different contexts: {0}
-
-# processor (006)
-ERR.015.006.0001= XMLPlan toString couldn''t print entire Program.
-ERR.015.006.0034= Unexpected symbol type while updating tuple: {0}
-ERR.015.006.0037= Tuple source does not exist: {0}
-ERR.015.006.0039= Instructed to abort processing when recursion limit reached.
-ERR.015.006.0042= No xml schema to validate document against
-ERR.015.006.0048= Fatal Error: {0}
-ERR.015.006.0049= Error: {0}
-ERR.015.006.0051= Invalid direction for MoveDocInstruction: {0}
-ERR.015.006.0054= Instructed to abort processing as default of choice.
-
-# rewriter (009)
-ERR.015.009.0001= Error evaluating criteria: {0}
-ERR.015.009.0002= Error translating criteria on the user''s command, the criteria translated to {0} is not valid
-ERR.015.009.0003= Error simplifying mathematical expression: {0}
-
-
-SQLParser.Unknown_join_type=Unknown join type: {0}
-SQLParser.Aggregate_only_top_level=Aggregate expressions are allowed only as top level functions in the SELECT and HAVING clauses.
-SQLParser.Unknown_agg_func=Unknown aggregate function: {0}
-SQLParser.Invalid_func=Invalid function name: [{0}]
-SQLParser.Integer_parse=Unable to parse integer literal: {0}
-SQLParser.Float_parse=Unable to parse floating point literal: {0}
-SQLParser.Invalid_id=Invalid metadata ID format: [{0}]
-SQLParser.Invalid_alias=Invalid alias format: [{0}]
-SQLParser.Invalid_short_name=Invalid simple identifier format: [{0}]
-SQLParser.Invalid_char={0} value must be a single character: [{1}].
-SQLParser.expected_non_reserved=Expected non-reserved word {0}, but was {1}.
-SystemSource.Add_desc=Add two numbers
-SystemSource.Add_result_desc=Left operand + right operand
-SystemSource.Subtract_desc=Subtract two numbers
-SystemSource.Subtract_result_desc=Left operand - right operand
-SystemSource.Multiply_desc=Multiply two numbers
-SystemSource.Multiply_result_desc=Left operand * right operand
-SystemSource.Divide_desc=Divide two numbers
-SystemSource.Divide_result_desc=Left operand / right operand
-SystemSource.Ceiling_desc=Ceiling of number
-SystemSource.Exp_desc=e^number
-SystemSource.Floor_desc=Floor of number
-SystemSource.Log_desc=Log (base e) of number
-SystemSource.Log10_desc=Log (base 10) of number
-SystemSource.Acos_desc=Arccosine of number
-SystemSource.Asin_desc=Arcsine of number
-SystemSource.Atan_desc=Arctan of number
-SystemSource.Atan2_desc=Arctan of number1 / number2
-SystemSource.Cos_desc=Cosine of number
-SystemSource.Cot_desc=Cotangent of number
-SystemSource.Degrees_desc=Convert from radians to degrees
-SystemSource.Pi_desc=Constant value for pi
-SystemSource.Radians_desc=Convert from degrees to radians
-SystemSource.Sin_desc=Sine of number
-SystemSource.Tan_desc=Tangent of number
-SystemSource.Bitand_desc=Bitwise AND of two integers
-SystemSource.Bitand_result_desc=integer1 AND integer2
-SystemSource.Bitor_desc=Bitwise inclusive OR of two integers
-SystemSource.Bitor_result_desc=integer1 OR integer2
-SystemSource.Bitxor_desc=Bitwise exclusive OR (XOR) of two integers
-SystemSource.Bitxor_result_desc=integer1 XOR integer2
-SystemSource.Bitnot_desc=Bitwise inversion (NOT) of a 32-bit integer. Equivalent to XOR(integer, 0xFFFFFFFF)
-SystemSource.Bitnot_result_desc=32-bit inverted integer
-SystemSource.Curdate_desc=Current date
-SystemSource.Curtime_desc=Current time
-SystemSource.Now_desc=Current timestamp
-SystemSource.Dayname_result_d_desc=Day name for date
-SystemSource.Dayname_result_ts_desc=Day name for timestamp
-SystemSource.Dayofmonth_result_d_desc=Day of month for date (1 = 1st)
-SystemSource.Dayofmonth_result_ts_desc=Day of month for timestamp (1 = 1st)
-SystemSource.Dayofweek_result_d_desc=Day of week for date (1 = Sunday)
-SystemSource.Dayofweek_result_ts_desc=Day of week for timestamp (1 = Sunday)
-SystemSource.Dayofyear_result_d_desc=Day of year for date (1 = Jan 1st)
-SystemSource.Dayofyear_result_ts_desc=Day of year for timestamp (1 = Jan 1st)
-SystemSource.Month_result_d_desc=Month for date (1 = January)
-SystemSource.Month_result_ts_desc=Month for timestamp (1 = January)
-SystemSource.Monthname_result_d_desc=Month name for date
-SystemSource.Monthname_result_ts_desc=Month name for timestamp
-SystemSource.Week_result_d_desc=Week of year for date
-SystemSource.Week_result_ts_desc=Week of year for timestamp
-SystemSource.Year_result_d_desc=Year for date
-SystemSource.Year_result_ts_desc=Year for timestamp
-SystemSource.Hour_result_t_desc=Hour for time
-SystemSource.Hour_result_ts_desc=Hour for timestamp
-SystemSource.Minute_result_t_desc=Minute for time
-SystemSource.Minute_result_ts_desc=Minute for timestamp
-SystemSource.Second_result_t_desc=Second for time
-SystemSource.Second_result_ts_desc=Second for timestamp
-SystemSource.Quarter_result_d_desc=Quarter for date (1=Jan/Feb/Mar)
-SystemSource.Quarter_result_ts_desc=Quarter for timestamp (1=Jan/Feb/Mar)
-SystemSource.Length_result=Length of string
-SystemSource.Ucase_result=Upper case of string
-SystemSource.Lcase_result=Lower case of string
-SystemSource.Lower_result=Lower case of string
-SystemSource.Upper_result=Upper case of string
-SystemSource.UcaseClob_result=Upper case of clob
-SystemSource.LcaseClob_result=Lower case of clob
-SystemSource.LowerClob_result=Lower case of clob
-SystemSource.UpperClob_result=Upper case of clob
-SystemSource.Left_result=Left trimmed string
-SystemSource.Right_result=Right trimmed string
-SystemSource.Formattime_desc=Convert to string
-SystemSource.Formattime_result_desc=Converted time
-SystemSource.Formatdate_desc=Convert to string
-SystemSource.Formatdate_result_desc=Converted date
-SystemSource.Formattimestamp_desc=Convert to string
-SystemSource.Formattimestamp_result_desc=Converted timestamp
-SystemSource.Parsetime_desc=Convert string to time
-SystemSource.Parsetime_result_desc=Time converted
-SystemSource.Parsedate_desc=Convert string to date
-SystemSource.Parsedate_result_desc=Date converted
-SystemSource.Parsetimestamp_desc=Convert string to timestamp
-SystemSource.Parsetimestamp_result_desc=Timestamp converted
-SystemSource.Formatinteger_desc=Convert to Integer
-SystemSource.Formatinteger_result_desc=Integer formatted
-SystemSource.Formatlong_desc=Convert to Long
-SystemSource.Formatlong_result_desc=Long formatted
-SystemSource.Formatdouble_desc=Convert to Double
-SystemSource.Formatdouble_result_desc=Double formatted
-SystemSource.Formatfloat_desc=Convert to Float
-SystemSource.Formatfloat_result_desc=Float formatted
-SystemSource.Formatbiginteger_desc=Convert to Big integer
-SystemSource.Formatbiginteger_result_desc=Big integer formatted
-SystemSource.Formatbigdecimal_desc=Convert to Big decimal
-SystemSource.Formatbigdecimal_result_desc=Big decimal formatted
-SystemSource.Parseinteger_desc=Parse to Integer
-SystemSource.Parseinteger_result_desc=Integer parsed
-SystemSource.Parselong_desc=Parse to Long
-SystemSource.Parselong_result_desc=Long parsed
-SystemSource.Parsedouble_desc=Parse to Double
-SystemSource.Parsedouble_result_desc=Double parsed
-SystemSource.Parsefloat_desc=Parse to Float
-SystemSource.Parsefloat_result_desc=Float parsed
-SystemSource.Parsebiginteger_desc=Parse to Biginteger
-SystemSource.Parsebiginteger_result_desc=Biginteger parsed
-SystemSource.Parsebigdecimal_desc=parse to Bigdecimal
-SystemSource.Parsebigdecimal_result_desc=Bigdecimal parsed
-SystemSource.Arith_left_op=Left operand
-SystemSource.Arith_right_op=Right operand
-SystemSource.Abs_desc=Absolute value of number
-SystemSource.Abs_arg=Number
-SystemSource.Abs_result_desc=Absolute value of number
-SystemSource.Rand_desc=Random Number
-SystemSource.Rand_arg=Number
-SystemSource.Rand_result_desc=Generated Random Number
-SystemSource.Double_arg2=Number
-SystemSource.Atan_arg1=Number parameter1 
-SystemSource.Atan_arg2=Number parameter2 
-SystemSource.Mod_desc=Modulus of two numbers
-SystemSource.Mod_result_desc=Left operand mod right operand
-SystemSource.Power_desc=Raise base to power
-SystemSource.Power_arg1=Base
-SystemSource.Power_arg2=Power
-SystemSource.Power_result_desc=Base ^ Power
-SystemSource.Round_desc=Round number to specified places
-SystemSource.Round_arg1=Numbers
-SystemSource.Round_arg2=Places
-SystemSource.Round_result_desc=Number rounded to specified places
-SystemSource.Sign_desc=Sign of number: 1 if number>0, 0 if number==0, -1 if number<0
-SystemSource.Sign_arg1=Number
-SystemSource.Sign_result_desc=Sign of number
-SystemSource.Sqrt_desc=Square root of number
-SystemSource.Sqrt_arg1=Number
-SystemSource.Sqrt_result_desc=Square root of number
-SystemSource.Timestampadd_d_desc=Add count number of interval type to date
-SystemSource.Timestampadd_d_arg1=Interval type
-SystemSource.Timestampadd_d_arg2=Count number
-SystemSource.Timestampadd_d_arg3=Date type
-SystemSource.Timestampadd_d_result_desc=Returned modified date
-SystemSource.Timestampadd_t_desc=Add count number of interval type to time
-SystemSource.Timestampadd_t_arg1=Interval type
-SystemSource.Timestampadd_t_arg2=Count number
-SystemSource.Timestampadd_t_arg3=Time type
-SystemSource.Timestampadd_t_result_desc=Returned modified time
-SystemSource.Timestampadd_ts_desc=Add count number of interval type to timestamp
-SystemSource.Timestampadd_ts_arg1=Interval type
-SystemSource.Timestampadd_ts_arg2=Count number
-SystemSource.Timestampadd_ts_arg3=Timestamp type
-SystemSource.Timestampadd_ts_result=Returned modified timestamp
-SystemSource.Timestampdiff_ts_desc=Calculate estimated number of intervals between start and end timestamp
-SystemSource.Timestampdiff_ts_arg1=Interval type
-SystemSource.Timestampdiff_ts_arg2=Start timestamp
-SystemSource.Timestampdiff_ts_arg3=End timestamp
-SystemSource.Timestampdiff_ts_result_desc=Returns estimated number of intervals between start and end timestamp
-SystemSource.TimestampCreate_desc=Create timestamp from a date and a time
-SystemSource.TimestampCreate_arg1=Date
-SystemSource.TimestampCreate_arg2=Time
-SystemSource.TimestampCreate_result_desc=Timestamp built from date and time
-SystemSource.Stringfunc_arg1=String
-SystemSource.Clobfunc_arg1=Clob
-SystemSource.Concat_desc=Concatenate left and right strings
-SystemSource.Concat_arg1=Left string
-SystemSource.Concat_arg2=Right string
-SystemSource.Concat_result_desc=Concatenated strings
-SystemSource.Concatop_desc=Concatenate left and right strings
-SystemSource.Concatop_arg1=Left string
-SystemSource.Concatop_arg2=Right string
-SystemSource.Concatop_result_desc=Concatenated strings
-SystemSource.Substring_desc=Substring of string, starting at index, of length
-SystemSource.Substring_arg1=String
-SystemSource.Substring_arg2=Starting index
-SystemSource.Substring_arg3=Length of substring
-SystemSource.Substring_result=Substring
-SystemSource.Susbstring2_desc=Substring of string, starting at index, to end of string
-SystemSource.Substring2_arg1=String
-SystemSource.Substring2_arg2=Starting index
-SystemSource.Substring2_result=Substring
-SystemSource.Left_desc=First length characters of string
-SystemSource.Left_arg1=String
-SystemSource.Left_arg2=Length of substring
-SystemSource.Left2_result=First length characters of string
-SystemSource.Right_desc=Last length characters of string
-SystemSource.Right_arg1=String
-SystemSource.Right_arg2=Length of substring
-SystemSource.Right2_result=Last length characters of string
-SystemSource.Locate_desc=Find index of substring in string starting at index
-SystemSource.Locate_arg1=Substring to find
-SystemSource.Locate_arg2=String
-SystemSource.Locate_arg3=Starting index
-SystemSource.Locate_result=Index of substring or -1 if not found
-SystemSource.Locate2_desc=Find index of substring in string
-SystemSource.Locate2_arg1=Substring to find
-SystemSource.Locate2_arg2=String
-SystemSource.Locate2_result=Index of substring or -1 if not found
-SystemSource.Replace_desc=Replace any substring in string with replacement
-SystemSource.Replace_arg1=String
-SystemSource.Replace_arg2=Substring to match
-SystemSource.Replace_arg3=Replacement string
-SystemSource.Replace_result=String with replacements
-SystemSource.Repeat_desc=Repeat string with count times
-SystemSource.Repeat_arg1=String
-SystemSource.Repeat_arg2=Count times to repeat
-SystemSource.Repeat_result=String repeated with count times
-SystemSource.Space_desc=Repeat space count times
-SystemSource.Space_arg1=Number of times to repeat
-SystemSource.Space_result=Space repeated count times
-SystemSource.Insert_desc=Insert string2 into string1 by deleting length characters at start and inserting string2
-SystemSource.Insert_arg1=Initial string
-SystemSource.Insert_arg2=Starting position
-SystemSource.Insert_arg3=Number of characters to delete at start
-SystemSource.Insert_arg4=String to insert
-SystemSource.Insert_result=Inserted string
-SystemSource.Ascii_desc=Takes a character and returns the ASCII or unicode integer representation
-SystemSource.Ascii_arg1=String
-SystemSource.Ascii_result=Character value
-SystemSource.Ascii2_desc=Takes a character and returns the ASCII or unicode integer representation
-SystemSource.Ascii2_arg1=Character
-SystemSource.Ascii2_result=Character value
-SystemSource.Chr_desc=Takes a unicode or ASCII value and returns the character representation
-SystemSource.Chr_arg1=Code value
-SystemSource.Chr_result=Character representation
-SystemSource.Char_desc=Takes a unicode or ASCII value and returns the character representation
-SystemSource.Char_arg1=Code value
-SystemSource.Char_result=Character representation
-SystemSource.Initcap_desc=Capitalizes each word (each letter after whitespace)
-SystemSource.Initcap_arg1=Input string
-SystemSource.Initcap_result=Result string
-SystemSource.Lpad_desc=Pad the input string on the left to length
-SystemSource.Lpad_arg1=String
-SystemSource.Lpad_arg2=Padded length
-SystemSource.Lpad_result=Padded string
-SystemSource.Lpad3_desc=Pad the input string on the left to length with pad character
-SystemSource.Lpad3_arg1=String
-SystemSource.Lpad3_arg2=Padded length
-SystemSource.Lpad3_arg3=Pad character
-SystemSource.Lpad3_result=Padded string
-SystemSource.Rpad1_desc=Pad the input string on the right to length
-SystemSource.Rpad1_arg1=String
-SystemSource.Rpad1_arg2=Padded length
-SystemSource.Rpad1_result=Padded string
-SystemSource.Rpad3_desc=Pad the input string on the right to length with pad character
-SystemSource.Rpad3_arg1=String
-SystemSource.Rpad3_arg2=Padded length
-SystemSource.Rpad3_arg3=Pad character
-SystemSource.Rpad3_result=Padded string
-SystemSource.Translate_desc=Translate the input string by converting characters in the source string to characters in the destination string
-SystemSource.Translate_arg1=String
-SystemSource.Translate_arg2=Source string
-SystemSource.Translate_arg3=Destination string
-SystemSource.Translate_result=Translated string
-SystemSource.Convert_arg1=Source value
-SystemSource.Convert_arg2=Target type
-SystemSource.Convert_result=Converted value
-SystemSource.Context_desc=Evaluate XML expression in the context of a different mapping level
-SystemSource.Context_arg1=XML context tag
-SystemSource.Context_arg2=XML element
-SystemSource.Context_result=Expression in higher context
-SystemSource.Rowlimit_desc=Limit the number of rows from an XML mapping class
-SystemSource.RowlimitException_desc=Limit the number of rows from an XML mapping class, throw Exception if passed
-SystemSource.Rowlimit_arg1=XML tag in the scope of a mapping class
-SystemSource.Rowlimit_result=Number of rows to be limited to
-SystemSource.Decode1_desc=Map the input value to a comma-separated list of allowed output values
-SystemSource.Decode1_arg1=Input column for decode
-SystemSource.Decode1_arg2=The comma delimited String that represents the mapping between input column value and output values.
-SystemSource.Decode1_result=The decoded value from the decode string.
-SystemSource.Decode2_desc=Map the input value to a delimiter-separated list of allowed output values
-SystemSource.Decode2_arg1=Input column for decode
-SystemSource.Decode2_arg2=The comma delimited String that represents the mapping between input column value and output values.
-SystemSource.Decode2_arg3=Decode String delimiter character(s)
-SystemSource.Decode2_result=The decoded value from the decode string.
-SystemSource.Lookup_desc=Look up a value in a cached code table
-SystemSource.Lookup_arg1=Full group name of code table
-SystemSource.Lookup_arg2=Short name of return element in code table
-SystemSource.Lookup_arg3=Short name of key element in code table
-SystemSource.Lookup_arg4=Key value to lookup
-SystemSource.Lookup_result=Return value for key as specified in code table
-SystemSource.User_desc=Get current user name 
-SystemSource.User_result=Return user name
-SystemSource.current_database_desc=Get current database name
-current_database_result=Returns the catalog name
-SystemSource.Env_desc=Get the value of an environment variable 
-SystemSource.Env_varname=Name of the environment variable
-SystemSource.Env_result=Return the string value of the environment variable
-SystemSource.Nvl_desc=Specifies a value to use instead if the input value is null
-SystemSource.Nvl_arg1=Value to check
-SystemSource.Nvl_arg2=Returned if value is null
-SystemSource.Nvl_result=Value or valueIfNull if value is null
-SystemSource.Ifnull_desc=Specifies a value to use instead if the input value is null
-SystemSource.Ifnull_arg1=Value to check
-SystemSource.Ifnull_arg2=Returned if value is null
-SystemSource.Ifnull_result=Value or valueIfNull if value is null
-SystemSource.Formattime_arg1=Time input
-SystemSource.Formattime_arg2=Time format
-SystemSource.Formatdate_arg1=Date input
-SystemSource.Formatdate_arg2=Date format
-SystemSource.Formattimestamp_arg1=Timestamp input
-SystemSource.Formattimestamp_arg2=Timestamp format
-SystemSource.Parsetime_arg1=String input
-SystemSource.Parsetime_arg2=Time format
-SystemSource.Parsedate_arg1=String input
-SystemSource.Parsedate_arg2=Date format
-SystemSource.Parsetimestamp_arg1=String input
-SystemSource.Parsetimestamp_arg2=Timestamp format
-SystemSource.Formatnumber_arg1=String input
-SystemSource.Formatnumber_arg2=Number format
-SystemSource.Parsenumber_arg1=String input
-SystemSource.Parsenumber_arg2=Parse format
-SystemSource.Bitfunc_arg1=Integer parameter
-SystemSource.Bitfunc2_arg1=First integer
-SystemSource.Bitfunc2_arg2=Second integer
-SystemSource.Convert_desc=Convert from {0} to target type
-SystemSource.xpathvalue_description=Retrieve the first match content for an XPath statement
-SystemSource.xpath_param1=Source document
-SystemSource.xpath_param2=XPath expression
-SystemSource.xpathvalue_result=Single result
-SystemSource.xsltransform_description=Transform the document with the given stylesheet. 
-SystemSource.xsltransform_param1=Source document
-SystemSource.xsltransform_param2=XSL stylesheet
-SystemSource.xsltransform_result=Clob result
-SystemSource.xmlconcat_description=Concat XML types. 
-SystemSource.xmlconcat_param1=First element
-SystemSource.xmlcomment_description=Create an XML comment. 
-SystemSource.xmlconcat_param1=String comment
-SystemSource.xmlconcat_result=XML result
-SystemSource.xmlpi_description=Create an XML processing instruction. 
-SystemSource.xmlpi_param1=Target
-SystemSource.xmlpi_param2=Content
-SystemSource.xmlpi_result=XML result
-SystemSource.jsonToXml_description=Create an XML document representing the given JSON. 
-SystemSource.jsonToXml_param1=Root element name
-SystemSource.jsonToXml_param2=JSON
-SystemSource.jsonToXml_result=XML result
-SystemSource.modifyTimeZone_description=Modify the time zone of this timestamp by adding or subtracting time
-SystemSource.modifyTimeZone_param1=Timestamp
-SystemSource.modifyTimeZone_param2=Starting time zone
-SystemSource.modifyTimeZone_param3=Ending time zone
-SystemSource.modifyTimeZone_result=Original timestamp with time added or subtracted to give the equivalent time in a different time zone
-SystemSource.CommandPayload_desc0=Retrieve the command payload as a string
-SystemSource.CommandPayload_desc1=Retrieve a property from the command payload, passed as a Properties object
-SystemSource.CommandPayload_result=The property value from the command payload 
-SystemSource.CommandPayload_property=The property name
-SystemSource.hasRole_description=Determine if the caller has the given role
-SystemSource.hasRole_param1=Role type
-SystemSource.hasRole_param2=Role name
-SystemSource.hasRole_result=whether the caller is in the given role
-SystemSource.from_unixtime_description=Return the Unix timestamp (in seconds) as a Timestamp value 
-SystemSource.from_unixtime_param1=Unix timestamp (in seconds)
-SystemSource.from_unixtime_result=Timestamp value
-SystemSource.nullif_description=Equivalent to case when (param1 = param2) then null else param1 
-SystemSource.nullif_param1=First parameter
-SystemSource.nullif_result=null if the parameters are equivalent else param1
-SystemSource.coalesce_description=Returns the first non-null parameter
-SystemSource.coalesce_param1=parameter
-SystemSource.coalesce_result=The first non-null parameter
-SystemSource.encode_desc=Converts a Blob to the appropriate chars
-SystemSource.encode_arg1=Blob
-SystemSource.encode_arg2=char representation Clob
-SystemSource.encode_result=Clob char rep
-SystemSource.decode_desc=Converts a Clob to the appropriate bytes
-SystemSource.decode_arg1=Clob
-SystemSource.decode_arg2=The encoding
-SystemSource.decode_result=byte representation Blob
-SystemSource.session_id_desc=Returns the session id of the currently logged in user 
-SystemSource.session_id_result=Returns the session id of the currently logged in user
-TempMetadataAdapter.Element_____{0}_____not_found._1=Element ''{0}'' not found.
-TempMetadataAdapter.Group_____{0}_____not_found._1=Group ''{0}'' not found.
-ExpressionEvaluator.Must_push=Function {0} is marked in the function metadata as a function that must be evaluated at the source.
-ExpressionEvaluator.Eval_failed=Unable to evaluate {0}: {1}
-XMLSerialize.resolvingError=XMLSerialize is valid only for XML expressions: {0}
-Evaluator.xmlserialize=XMLSerialize: data exception - not an xml document
-Evaluator.xmlquery=Error evaluating XMLQuery: {0}
-ExecResolver.Param_convert_fail=Unable to convert procedural parameter of type {0} to expected type {1}
-ExecResolver.return_expected=Procedure {0} does not have a return value.
-ExecResolver.out_type_mismatch=OUT/RETURN parameter {0} with type {1} cannot be converted to {2}
-DynamicCommandResolver.SQL_String=Expected dynamic command sql to be of type STRING instead of type {0}.
-UnionQueryResolver.type_conversion=The Expression {0} used in a nested UNION ORDER BY clause cannot be implicitly converted from type {1} to type {2}.
-ValidationVisitor.select_into_no_implicit_conversion=There is no implicit conversion between the source element type ({0}) and the target element type ({1}) at position {2} of the query: {3}
-ValidationVisitor.excpet_intersect_all=EXCEPT ALL and INTERSECT ALL are currently unsupported
-ValidationVisitor.element_updates_not_allowed=Metadata does not allow updates on the element: {0}
-ValidationVisitor.invalid_batch_command=Only INSERT, UPDATE, DELETE, and SELECT ... INTO statements are allowed within a batch.
-ValidationVisitor.badoffset2=The row offset in the LIMIT clause must be >= 0
-ValidationVisitor.badlimit2=The row limit in the LIMIT clause must be >= 0
-ValidationVisitor.invalid_scalar_group_reference=Cannot reference a scalar group as a table: {0}
-ValidationVisitor.select_into_wrong_elements=Wrong number of elements being SELECTed INTO the target table. Expected {0} elements, but was {1}.
-SimpleQueryResolver.Query_was_redirected_to_Mat_table=The query against {0} was redirected to the materialization table {1}.
-SimpleQueryResolver.ambiguous_all_in_group=The symbol {0} refers to more than one group defined in the FROM clause.
-SimpleQueryResolver.Proc_Relational_Name_conflict=Cannot access procedure {0} using table semantics since the parameter and result set column names are not all unique.
-QueryResolver.invalid_xpath=Invalid xpath value: {0}
-ResolveVariablesVisitor.reserved_word_for_temporary_used=Cursor names cannot begin with "#" as that indicates the name of a temporary table: {0}.
-SimpleQueryResolver.materialized_table_not_used=The query against {0} did not use materialization table {1} due to the use of OPTION NOCACHE.
-SimpleQueryResolver.cache_hint_used=Loading materialized view {1} for view {0} using cache hint {2}.
-SimpleQueryResolver.procedure_cache_used=Procedure caching will be used for {0}.
-SimpleQueryResolver.procedure_cache_not_usable=Procedure caching will not be used for {0} since the result set cache is disabled or the results/parameters cannot be cached.
-SimpleQueryResolver.procedure_cache_not_used=Procedure caching will not be used for {0} due to the use of OPTION NOCACHE.
-ValidationVisitor.groupby_subquery=Expressions used in a GROUP BY cannot be constant and must not contain subqueries: "{0}".
-ValidationVisitor.Procedure_should_have_query=Procedure must execute at least one command to define the procedure result set.
-ValidationVisitor.Procedure_has_group_self_reference=Procedure cannot have a Group reference to itself.
-ExpressionEvaluator.Expected_props_for_payload_function=Unable to evaluate {0}: expected Properties for command payload but got object of type {1}
-ValidationVisitor.The_rowlimit_function_cannot_be_used_in_a_non-XML_command=The ''rowlimit'' and ''rowlimitexception'' functions cannot be used in a non-XML command
-ValidationVisitor.The_context_function_cannot_be_used_in_a_non-XML_command=The ''context'' function cannot be used in a non-XML command
-ValidationVisitor.0=The ''rowlimit'' and ''rowlimitexception'' functions cannot be nested within other functions.
-ValidationVisitor.1=The ''rowlimit'' and ''rowlimitexception'' functions operand must be a constant nonnegative integer.
-ValidationVisitor.2=The ''rowlimit'' and ''rowlimitexception'' functions arg must be an XML node symbol
-ValidationVisitor.3=''Rowlimit'' and ''rowlimitexception'' functions can only be used within a compare criteria which is entirely a single conjunct.
-ValidationVisitor.Context_function_nested=Context functions cannot be nested
-ERR.015.004.0036= First argument in ''context'' must be the name of a node in the XML document model.  Found Object {0} of Class {1}
-ExecResolver.invalid_named_params=Invalid param name(s): {0}.  Name(s) of params without explicit values: {1}  
-ExecResolver.duplicate_named_params=Duplicate named param ''{0}''
-ResolverUtil.required_param=Required parameter ''{0}'' has no value was set or is an invalid parameter.
-ResolverUtil.duplicateName=Cannot create group ''{0}'' with multiple columns named ''{1}''
-ResolverUtil.error_converting_value_type=Exception converting value {0} of type {1} to expected type {2}
-ResolverUtil.setquery_order_expression=ORDER BY expression ''{0}'' cannot be used with a set query.
-ResolverUtil.invalid_unrelated=Unrelated order by column {0} cannot be used in a SET query, with SELECT DISTINCT, or GROUP BY
-XMLQueryResolver.xml_only_valid_alone=If any symbol in SELECT clause is ''xml'' or group.''xml'' , then no other element is allowed.
-ResolveVariablesVisitor.datatype_for_the_expression_not_resolvable=The datatype for the expression was not resolvable.
-TempTableResolver.unqualified_name_required=Cannot create temporary table "{0}". Local temporary tables must be created with unqualified names.
-TempTableResolver.table_already_exists=Cannot create temporary table "{0}". A table with the same name already exists.
-ValidationVisitor.drop_of_nontemptable=Cannot drop a non temporary table "{0}".							
-ValidationVisitor.orderby_expression_xml=XML queries cannot order by an expression.
-ValidationVisitor.text_table_invalid_width=For a fixed width text table, all columns must have width set.
-ValidationVisitor.text_table_width=Fixed width text tables should not have DELIMITER, QUOTE, ESCAPE, or HEADER specified.
-ValidationVisitor.text_table_negative=Text table WIDTH, HEADER, or SKIP values must not be negative. 
-ValidationVisitor.text_table_delimiter=Text DELIMITER cannot be the same as the QUOTE or ESCAPE characters.
-ValidationVisitor.text_table_newline=Text DELIMITER, QUOTE, and ESCAPE characters cannot be the new line character.
-ValidationVisitor.xml_namespaces=At most only one NO DEFAULT or DEFAULT namespace may be specified.
-ValidationVisitor.xml_namespaces_reserved=The namespaces xmlns and xml are reserved.
-ValidationVisitor.xml_namespaces_null_uri=The null uri, or empty string, is not allowed as the uri value.
-ValidationVisitor.xml_attributes_reserved=The namespace xmlns is reserved.
-ValidationVisitor.xml_content_type=The expression "{0}" is of OBJECT or BLOB type, which cannot be used as an XML or TEXT content value.
-ValidationVisitor.xml_invalid_qname=The qname "{0}" is invalid.
-ValidationVisitor.context_item_type=XMLTABLE or XMLQUERY PASSING context item must be an XML value.
-ValidationVisitor.passing_requires_name=XMLTABLE or XMLQUERY PASSING clause can only contain at most 1 unnamed item.
-ValidationVisitor.duplicate_passing=XMLTABLE or XMLQUERY PASSING clause duplicate item name "{0}".
-ValidationVisitor.one_ordinal=Only one FOR ORDINALITY column is allowed for an XMLTABLE.
-ValidationVisitor.invalid_default=XMLTABLE DEFAULT expression is invalid: "{0}"
-ValidationVisitor.context_required=The XQuery requires a context item, but none exists in the PASSING clause.
-ValidationVisitor.xmlserialize_type=XMLSERIALIZE expects a STRING, CLOB, or BLOB value.
-ValidationVisitor.invalid_encoding=Encoding {0} is not valid.
-ValidationVisitor.subquery_insert=SELECT INTO should not be used in a subquery.
-UpdateProcedureResolver.only_variables=Element symbol "{0}" cannot be assigned a value.  Only declared VARIABLES can be assigned values.
-MappingLoader.unknown_node_type=Unknown Node Type "{0}" being loaded by the XML mapping document.
-MappingLoader.invalid_criteria_node=Invalid criteria node found; A criteria node must have criteria specified or it must be a default node.
-WrongTypeChild=Wrong type of child node is being added.
-NoCriteria=Failed to add the node, because Criteria nodes must have "criteria" value set on them, or they need to be the default node.
-root_cannotbe_null=Root node assigned to a document can be null.
-invalid_recurive_node= Found recursive node {0} without recursive root node.
-SaxonXQueryExpression.bad_xquery=Failed to evaluate XQuery expression; Please check the query and correct errors in syntax or usage. 
-SaxonXQueryExpression.compile_failed=Could not compile XQuery; Please check the query for syntax or usage errors.
-SaxonXQueryExpression.invalid_path=Column "{0}" has an invalid path expression: {1} 
-SaxonXQueryExpression.bad_context=Error building Source for context item.
-MappingLoader.invalidName=Null or blank name found in the Mapping Document, Must have valid name. Re-build the VDB
-MatchCriteria.invalid_escape=Invalid escape sequence "{0}" with escape character "{1}"
-QueryUtil.wrong_number_of_values=The number of bound values ''{0}'' does not match the number of parameters ''{1}'' in the prepared statement.
-QueryUtil.Error_executing_conversion_function_to_convert_value=Error converting parameter number {0} with value "{1}" to expected type {2}.
-InsertResolver.cant_convert_query_type=Cannot convert insert query expression projected symbol ''{0}'' of type {1} to insert column ''{2}'' of type {3}
-SetClause.resolvingError=Cannot set symbol ''{1}'' with expected type {2} to expression ''{0}''
-NewCalculateCostUtil.badCost=Unexpected format encountered for max or min value
-
-WorkerPool.Max_thread=Reached maximum thread count "{0}" for worker pool "{1}" with a queue size of "{2}".
-WorkerPool.uncaughtException=Uncaught exception processing work
-
-
-TempTable.duplicate_key=Duplicate key
-ValidationVisitor.group_in_both_dep=Table specified in both dependent and independent queries '{0}'
-XMLQuery.resolvingError=Failed to resolve the query '{0}'
-SQLParser.non_position_constant=Invalid order by at {0} 
-
-
-QueryRewriter.infinite_while=Infinite loop detected, procedure will not be executed.
-
-BatchedUpdatePlanner.unrecognized_command=The batch contained an unrecognized command: {0}
-ProcedurePlanner.bad_stmt=Error while planning update procedure, unknown statement type encountered: {0}
-RulePushSelectCriteria.Error_getting_modelID=Error getting modelID
-XMLPlanner.no_uri=Cannot find namespace URI for namespace {0} of element {1}
-
-XMLPlanner.The_XML_document_element_{0}_is_not_mapped_to_data_and_cannot_be_used_in_the_ORDER_BY_clause__{1}_1=The XML document element {0} is not mapped to data and cannot be used in the ORDER BY clause: {1}
-XMLPlanner.The_rowlimit_parameter_{0}_is_not_in_the_scope_of_any_mapping_class=The ''rowlimit'' or ''rowlimitexception'' function parameter ''{0}'' is not an XML node within the scope of any mapping class.
-XMLPlanner.Criteria_{0}_contains_conflicting_row_limits=The criteria ''{0}'' contains conflicting row limits for an XML mapping class.
-AccessNode.rewrite_failed=Failed to rewrite the command: {0}
-BatchedUpdateNode.unexpected_end_of_batch=Unexpectedly reached the end of the batched update counts at {0}, expected {1}.
-row_limit_passed=The row limit {0} has been exceeded for XML mapping class {1}.
-AddNodeInstruction.element__1=element
-AddNodeInstruction.Unable_to_add_xml_{0}_{1},_namespace_{2},_namespace_declarations_{3}_3=Unable to add xml {0} {1}, namespace {2}, namespace declarations {3}
-QueryProcessor.request_cancelled=The request {0} has been cancelled.
-VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state=INPUT variables used in the expression should all have same CHANGING state: {0}
-
-ExecDynamicSqlInstruction.0=Evaluated dynamic SQL expression value was null.
-ExecDynamicSqlInstruction.3=There is a recursive invocation of group ''{0}''. Please correct the SQL.
-ExecDynamicSqlInstruction.4=The dynamic sql string contains an incorrect number of elements.
-ExecDynamicSqlInstruction.6=The datatype ''{0}'' for element ''{1}'' in the dynamic SQL cannot be implicitly converted to ''{2}''.
-ExecDynamicSqlInstruction.couldnt_execute=Couldn''t execute the dynamic SQL command "{0}" with the SQL statement "{1}" due to: {2}
-
-RulePlanJoins.cantSatisfy=Join region with unsatisfied access patterns cannot be satisfied by the join criteria, Access patterns: {0} 
-TempTableStore.table_exist_error=Temporary table "{0}" already exists.
-TempTableStore.table_doesnt_exist_error=Temporary table "{0}" does not exist.
-
-XMLQueryPlanner.cannot_plan=Cannot create a query for MappingClass with user criteria {0}
-CriteriaPlanner.staging_context=Staging table criteria cannot contian context functions
-CriteriaPlanner.multiple_staging=Staging table criteria {0} was not specified against a single staging table
-CriteriaPlanner.invalid_context=Element {0} is not in the scope of the context {1}
-CriteriaPlanner.invalid_element=Element {0} is not a valid data node
-results_not_found=Results for the mapping class {0} are not found; 
-RulePlanProcedures.no_values=No valid criteria specified for procedure parameter {0}
-ProcedurePlan.nonNullableParam=The procedure parameter is not nullable, but is set to null: {0}
- 
-FileStoreageManager.error_creating=Error creating {0}
-FileStoreageManager.error_reading=Error reading {0}
-FileStoreageManager.no_directory=No directory specified for the file storage manager.
-FileStoreageManager.not_a_directory={0} is not a valid storage manager directory.
-FileStoreageManager.space_exhausted=Max buffer space of {0} bytes has been exceed.  The current operation will be aborted.
-
-TextTableNode.no_value=No value found for column \"{0}\" in the row ending on text line {1} in {2}.
-TextTableNode.conversion_error=Could not convert value for column \"{0}\" in the row ending on text line {1} in {2}.
-TextTableNode.header_missing=HEADER entry missing for column name \"{0}\" in {1}. 
-TextTableNode.unclosed=Text parse error: Unclosed qualifier at end of text in {0}.
-TextTableNode.character_not_allowed=Text parse error: Non-whitespace character found between the qualifier and the delimiter in text line {0} in {1}.
-TextTableNode.unknown_escape=Text parse error: Unknown escape sequence \\{0} in text line {1} in {2}.
-TextTableNode.invalid_width=Text parse error: Fixed width line width {0} is smaller than the expected {1} on text line {2} in {3}.
-
-XMLTableNode.error=Error evaluating XQuery row context for XMLTable: {0}
-XMLTableNode.path_error=Error evaluating XMLTable column path expression for column: {0}
-XMLTableName.multi_value=Unexpected multi-valued result was returned for XMLTable column "{0}".  Path expressions for non-XML type columns should return at most a single result.
-
-TempTableDataManager.failed_load=Failed to load materialized view table {0}.
-TempTableDataManager.loaded=Loaded materialized view table {0} with row count {1}.
-TempTableDataManager.loading=Loading materialized view table {0}
-TempTableDataManager.not_implicit_matview={0} does not target an internal materialized view.
-TempTableDataManager.row_refresh_pk=Materialized view {0} cannot have a row refreshed since there is no primary key.
-TempTableDataManager.row_refresh_composite=Materialized view {0} cannot have a row refreshed because it uses a composite key.
-TempTableDataManager.row_refresh_updatable=Materialized view {0} cannot have a row refreshed because it's cache hint did not specify \"updatable\".
-TempTableDataManager.row_refresh=Refreshing row {1} for materialized view {0}.
-CriteriaPlanner.no_context=No root node found.
-
-BasicInterceptor.ProcessTree_for__4=ProcessTree for
-
-
-ConnectorManager.not_in_valid_state=Connector is not in OPEN state
-
-ConnectorManagerImpl.Initializing_connector=Initializing connector {0}
-Cancel_request_failed=AtomicRequest {0} failed to cancel.
-
-ConnectorWorker.MaxResultRowsExceed=The number of result rows has exceeded the maximum result rows "{0}"
-ConnectorWorker.zero_size_non_last_batch=Connector returned a 0 row non-last batch: {0}.
-ConnectorWorker.process_failed=Connector worker process failed for atomic-request={0}
-ConnectorWorker.ConnectorWorker_result_set_unexpected_columns=Could not process stored procedure results for {0}.  Expected {1} result set columns, but was {2}.  Please update your models to allow for stored procedure results batching.
-
-
-DataTierManager.could_not_obtain_connector_binding=Could not obtain connection factory for model {0} in VDB name= {1}, version {2}
-
-
-DQPCore.Unable_to_load_metadata_for_VDB_name__{0},_version__{1}=Unable to load metadata for VDB name= {0}, version= {1}
-DQPCore.Unknown_query_metadata_exception_while_registering_query__{0}.=Unknown query metadata exception while registering query: {0}.
-DQPCore.Clearing_prepared_plan_cache=Clearing prepared plan cache
-DQPCore.The_request_has_been_closed.=The request {0} has been closed.
-DQPCore.The_atomic_request_has_been_cancelled=The atomic request {0} has been canceled.
-DQPCore.failed_to_cancel=Failed to Cancel request, as request already finished processing
-
-ProcessWorker.failed_rollback=Failed to properly rollback autowrap transaction properly
-ProcessWorker.error=Unexpected exception for request {0}
-ProcessWorker.processing_error=Processing exception ''{0}'' for request {1}.  Exception type {2} thrown from {3}. Enable more detailed logging to see the entire stacktrace.
-
-
-# #query (018.005)
-ERR.018.005.0095 = User <{0}> is not entitled to action <{1}> for 1 or more of the groups/elements/procedures.
-
-# services (003)
-
-Request.Invalid_character_in_query=Bind variables (represented as "?") were found but are allowed only in prepared or callable statements.
-Request.no_result_set=The query does not return an update count.
-Request.result_set=The query does not return a result set.
-
-ProcessWorker.wrongdata=Wrong type of data found or no data found; expecting streamable object from the buffer manager.
-ProcessWorker.LobError=An error occurred during streaming of Lob Chunks to Client.
-
-TransactionServer.existing_transaction=Client thread already involved in a transaction. Transaction nesting is not supported. The current transaction must be completed first.
-TransactionServer.no_transaction=No transaction found for client {0}.
-TransactionServer.concurrent_transaction=Concurrent enlistment in global transaction {0} is not supported.
-TransactionServer.no_global_transaction=Expected an existing global transaction {0} but there was none for client {1}
-TransactionServer.unknown_flags=Unknown flags
-TransactionServer.no_global_transaction=No global transaction found for {0}.
-TransactionServer.wrong_transaction=Client is not currently enlisted in transaction {0}.
-TransactionServer.resume_failed=Cannot resume, transaction {0} was not suspended by client {1}.
-TransactionServer.existing_global_transaction=Global transaction {0} already exists.
-TransactionServer.suspended_exist=Suspended work still exists on transaction {0}.
-
-TransformationMetadata.does_not_exist._1=does not exist.
-TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1=Error trying to read virtual document {0}, with body \n{1}
-TransformationMetadata.Unknown_support_constant___12=Unknown support constant: 
-TransformationMetadata.QueryPlan_could_not_be_found_for_physical_group__6=QueryPlan could not be found for physical group 
-TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8=InsertPlan could not be found for physical group 
-TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10=InsertPlan could not be found for physical group 
-TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12=DeletePlan could not be found for physical group 
-TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1=Error trying to read schemas for the document/table : 
-TransformationMetadata.Invalid_type=Invalid type: {0}.
-TransformationMetadata.does_not_exist._1=does not exist.
-TransformationMetadata.0={0} ambiguous, more than one entity matching the same name
-TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1=Error trying to read virtual document {0}, with body \n{1}
-TransformationMetadata.Unknown_support_constant___12=Unknown support constant: 
-TransformationMetadata.QueryPlan_could_not_be_found_for_physical_group__6=QueryPlan could not be found for physical group 
-TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8=InsertPlan could not be found for physical group 
-TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10=InsertPlan could not be found for physical group 
-TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12=DeletePlan could not be found for physical group 
-TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1=Error trying to read schemas for the document/table : 
-TransformationMetadata.Invalid_type=Invalid type: {0}.
-
-CachedFinder.no_connector_found=No connector with jndi-name {0} found for Model {1} with source name {2} 
-translator_not_found=Translator {0} not accessible.
-datasource_not_found=Data Source {0} not accessible.
-
-RequestWorkItem.cache_nondeterministic=Caching command "{0}" at a session level, but less deterministic functions were evaluated. 
-not_found_cache=Results not found in cache
-failed_to_unwrap_connection=Failed to unwrap the source connection.
-connection_factory_not_found=Failed to the Connection Factory with JNDI name {0}. Please check the name for spelling or deploy the Connection Factory with specified name. 
-
-RelationalPlanner.nonpushdown_command=Source command "{0}" contains non-pushdown constructs. 
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/engine/src/main/resources/org/teiid/query/i18n.properties (from rev 2707, branches/7.2.x/engine/src/main/resources/org/teiid/query/i18n.properties)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/main/resources/org/teiid/query/i18n.properties	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/main/resources/org/teiid/query/i18n.properties	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,886 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership.  Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+# 
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+# 
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
+# 
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
+
+# Error messages for query (015) project to address internationalization
+# Format:
+#
+
+# function (001)
+ERR.015.001.0002 = Cannot find implementation for known function {0}
+ERR.015.001.0003 = Error while evaluating function {0}
+ERR.015.001.0004 = Unable to access function implementation for [{0}]
+ERR.015.001.0005 = ERROR loading system functions: {0}
+ERR.015.001.0017 = Left count is invalid: {0}
+ERR.015.001.0025 = Pad length must be > 0.
+ERR.015.001.0027 = Pad string for lpad/rpad must have length greater than 0.
+ERR.015.001.0031 = Source and destination character lists must be the same length.
+ERR.015.001.0033 = Error converting [{0}] of type {1} to type {2}
+ERR.015.001.0035 = The context function may only be used in XML queries.
+ERR.015.001.0035a = The rowlimit and rowlimitexception functions may only be used in XML queries.
+ERR.015.001.0042 = Illegal argument for formating: {0}
+ERR.015.001.0043 = Parse Exception occurs for executing: {0} {1}
+ERR.015.001.0044 = Function metadata source is of invalid type: {0}
+ERR.015.001.0045 = Function method is of invalid type: {0}
+ERR.015.001.0046 = The function "{0}" will not be added because a function with the same name and signature already exists.
+ERR.015.001.0047 = Unexpected exception while loading "{1}.{2}" for UDF "{0}"
+FunctionTree.not_void = UDF "{0}" method "{1}" must not return void.
+FunctionTree.not_public = UDF "{0}" method "{1}" must be public.
+FunctionTree.not_static = UDF "{0}" method "{1}" must be static.
+FunctionTree.no_class = Could not load UDF "{0}", since its invocation class "{1}" could not be found.
+FunctionTree.no_method = UDF "{0}" could not loaded, since no method on class "{1}" with name "{2}" has a matching type signature.
+ERR.015.001.0048 = Unable to represent average value from {0} / {1}
+ERR.015.001.0050 = Unable to compute aggregate function {0} on data of type {1}
+ERR.015.001.0052 = {0} must be non-null.
+ERR.015.001.0053 = Method parameter must be non-null.
+ERR.015.001.0054 = Type is unknown: {0}
+ERR.015.001.0055 = {0} exceeds maximum length of {1}
+ERR.015.001.0056 = {0} has invalid first character: {1}
+ERR.015.001.0057 = {0} has invalid character: {1}
+ERR.015.001.0058 = {0} cannot end with a ''.''
+ERR.015.001.0061 = <start> value of {0} is invalid, which should never be less than zero or bigger than the length of original string {1}
+ERR.015.001.0062 = <length> value of {0} is invalid, which should never less be than zero.
+ERR.015.001.0063 = Input String is an empty string but start value or/and length value is bigger than zero.
+ERR.015.001.0066 = Unknown type signature for evaluating function of: {0} ({1})
+ERR.015.001.0069 = Unknown type signature for evaluating function of: {0} ({1})
+
+# mapping (002)
+ERR.015.002.0009 = Search direction arg ''{0}'' is not one of the search constants defined in MappingNodeConstants.
+ERR.015.002.0010 = Value for property ''{0}'' is null.
+ERR.015.002.0011 = Invalid type: {0}
+
+
+# parser (005)
+QueryParser.emptysql=Parser cannot parse an empty sql statement.
+QueryParser.parsingError=Parsing error: {0}
+QueryParser.nullSqlCrit=Parser cannot parse a null sql criteria.
+QueryParser.lexicalError= Lexical error: {0}
+QueryParser.nullSqlExpr= Parser cannot parse a null sql expression.
+QueryParser.xqueryCompilation= Direct usage of XQuery is no longer supported, use XMLQUERY instead.
+
+# processor (006)
+ERR.015.006.0010= Unknown criteria type: {0}
+ERR.015.006.0011= Unable to evaluate {0} expression of {1}
+ERR.015.006.0012= Unknown compare criteria operator: {0}
+ERR.015.006.0014= Failed to create regular expression from match pattern: {0}. {1}
+ERR.015.006.0015= Unable to evaluate expression of {0}
+ERR.015.006.0016= Unknown expression type: {0}
+ERR.015.006.0033= Unable to evaluate {0}: {1}
+ERR.015.006.0055= Unable to evaluate LOOKUP function.
+ERR.015.006.0057= Unknown subquery comparison predicate quantifier: {0}
+ERR.015.006.0058= The command of this scalar subquery returned more than one value: {0}
+
+# report (007)
+ERR.015.007.0001= Item may not be null
+
+# resolver (008)
+ERR.015.008.0003= Only one XML document may be specified in the FROM clause of a query.
+ERR.015.008.0007= Incorrect number of parameters specified on the stored procedure {2} - expected {0} but got {1}
+ERR.015.008.0009= {1} is not allowed on the virtual group {0}: no {1} procedure was defined.
+ERR.015.008.0010= INSERT statement must have the same number of elements and values specified.  This statement has {0} elements and {1} values.
+ERR.015.008.0011= Error parsing query plan transformation for {0}
+ERR.015.008.0012= Unable to resolve update procedure as the virtual group context is ambiguous.
+ERR.015.008.0013= Error parsing query plan transformation for {0}
+ERR.015.008.0015= Unknown statement type: {0}
+ERR.015.008.0019= Unable to resolve element: {0}
+ERR.015.008.0020= Element is ambiguous and must be qualified: {0}
+ERR.015.008.0022= Failed parsing reference binding: {0}
+ERR.015.008.0025= Binding reference cannot be a function: {0}
+ERR.015.008.0026= Expression ''{0}'' has a parameter with non-determinable type information.  The use of an explicit convert may be necessary.
+ERR.015.008.0027= The expressions in this criteria are being compared but are of differing types ({0} and {1}) and no implicit conversion is available:  {2}
+ERR.015.008.0029= This criteria must have string or CLOB expressions on each side: {0}
+ERR.015.008.0030= Type cannot be null for expression: {0}
+ERR.015.008.0031= This criteria must have values only of the same type as the left expression: {0}
+ERR.015.008.0032= There must be exactly one projected symbol of the subquery: {0}
+ERR.015.008.0033= The left expression must have a type convertible to the type of the subquery projected symbol: {0}
+ERR.015.008.0035= Type was null for {0} in function {1}
+ERR.015.008.0036= The function ''{0}'' has more than one possible signature.
+ERR.015.008.0037= The conversion from {0} to {1} is not allowed.
+ERR.015.008.0039= The function ''{0}'' is an unknown form.  Check that the function name and number of arguments is correct.
+ERR.015.008.0040= The function ''{0}'' is a valid function form, but the arguments do not match a known type signature and cannot be converted using implicit type conversions.
+ERR.015.008.0041= Expected value of type ''{0}'' but ''{1}'' is of type ''{2}'' and no implicit conversion is available.
+ERR.015.008.0042= Element ''{0}'' in ORDER BY is ambiguous and may refer to more than one element of SELECT clause.
+ERR.015.008.0043= Element ''{0}'' in ORDER BY was not found in SELECT clause.
+ERR.015.008.0045= Failed parsing insert plan for {0}
+ERR.015.008.0046= The symbol {0} may only be used once in the FROM clause.
+ERR.015.008.0047= The symbol {0} refers to a group not defined in the FROM clause.
+ERR.015.008.0049= Bindings must be specified
+ERR.015.008.0051= Symbol {0} is specified with an unknown group context
+ERR.015.008.0053= Element "{0}" is ambiguous, it exists in two or more groups.
+ERR.015.008.0054= Element "{0}" is not defined by any relevant group.
+ERR.015.008.0055= Group specified is ambiguous, resubmit the query by fully qualifying the group name
+ambiguous_procedure= Procedure ''{0}'' is ambiguous, use the fully qualified name instead
+ERR.015.008.0056= Group does not exist
+ERR.015.008.0061= Unable to resolve stored procedure {0} the datatype for the parameter {1} is not specified.
+ERR.015.008.0062= Unable to resolve return element referred to by LOOKUP function: {0}
+ERR.015.008.0063= The first three arguments for the LOOKUP function must be specified as constants.
+ERR.015.008.0065= Group {0} is not allowed in LOOKUP function.
+ERR.015.008.0068= Could not find a common type to which all {0} expressions can be implicitly converted: {1}
+ERR.015.008.0070= Aliased Select Symbols are not valid in XML Queries.
+XMLQueryResolver.no_expressions_in_select=Expressions cannot be selected by XML Queries
+
+# sql (010)
+ERR.015.010.0001= Invalid compare operator: {0}
+ERR.015.010.0002= Invalid logical operator: {0}
+ERR.015.010.0003= Cannot set null collection of elements on GroupBy
+ERR.015.010.0006= Invalid parameter type [{0}] must be IN, OUT, INOUT, RETURN_VALUE, RESULT_SET
+ERR.015.010.0009= No columns exist.
+ERR.015.010.0010= Invalid column index: {0}
+ERR.015.010.0011= Parameter cannot be null
+ERR.015.010.0014= Constant type should never be null
+ERR.015.010.0015= Unknown constant type: {0}
+ERR.015.010.0016= A group symbol may not resolve to a null metadata ID.
+ERR.015.010.0017= The name of a symbol may not be null.
+ERR.015.010.0018= Inconsistent number of elements in transformation projected symbols and virtual group.
+ERR.015.010.0021= Elements cannot be null
+ERR.015.010.0022= Functions cannot be null
+ERR.015.010.0023= Groups cannot be null
+ERR.015.010.0029= Cannot create AliasSymbol wrapping AliasSymbol
+ERR.015.010.0031= Illegal variable name ''{1}''.  Variable names can only be prefixed with the special group name ''{0}''.
+ERR.015.010.0032= Variable {0} was previously declared.
+ERR.015.010.0035= The <expression> cannot be null in CASE <expression>
+ERR.015.010.0036= There must be at least one WHEN expression and one THEN expression. The number of WHEN and THEN expressions must be equal.
+ERR.015.010.0037= The WHEN part of the CASE expression must contain an expression.
+ERR.015.010.0038= The THEN part of the CASE expression must contain an expression
+ERR.015.010.0039= The WHEN part of the searched CASE expression must contain a criteria.
+
+# util (011)
+
+# validator (012)
+ERR.015.012.0001 = The query defining an updatable virtual group cannot be a UNION query
+ERR.015.012.0002 = The query defining an updatable virtual group cannot be a stored query or stored procedure execution
+ERR.015.012.0003 = The query defining an updatable virtual group cannot be an INSERT
+ERR.015.012.0004 = The query defining an updatable virtual group cannot be an UPDATE
+ERR.015.012.0005 = The query defining an updatable virtual group cannot be a DELETE
+ERR.015.012.0006 = The query defining an updatable virtual group should not use GROUP BY or HAVING.
+ERR.015.012.0007 = The query defining an updatable virtual group cannot use a non-constant, non-column reference expressions in its SELECT clause {0}.
+ERR.015.012.0009 = The query defining an updatable virtual group cannot have more than one group in its FROM clause {0}
+ERR.015.012.0010 = The query defining an updatable simple virtual group should select all the required elements in its FROM clause {0}
+ERR.015.012.0011 = There must be exactly one projected symbol in the subcommand of an IN clause.
+ERR.015.012.0012 = An AssignmentStatement cannot change the value of a {0} or {1} variable.
+ERR.015.012.0016 = Variable {0} not assigned any value in this procedure.
+ERR.015.012.0017 = Variables declared the procedure''s DeclareStatement cannot be one of the special variables: {0}, {1} and {2}.
+ERR.015.012.0019 = TranslateCriteria cannot be used in on an if or while statement.
+ERR.015.012.0020 = Elements used on the criteria of an if or while statement should be variables declared in the procedure, virtual group elements can be used in the HAS Criteria
+ERR.015.012.0021 = Element being translated in the WITH clause not among the elements on the ON clause of the TranslateCriteria.
+ERR.015.012.0022 = Unable to translate criteria on the update command against the virtual group, the element {0} is mapped to an aggregate symbol in the virtual group''s query transform, and cannot be translated.
+ERR.015.012.0023 = Unable to translate criteria on the update command against the virtual group, the element {0} is mapped to an expression whose elements are not present on the command in the procedure using the translated criteria.
+ERR.015.012.0024 = The following data elements are not supported in the SELECT clause: {0}.
+ERR.015.012.0025 = Command must project at least one symbol
+ERR.015.012.0026 = Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in SELECT DISTINCT, ORDER BY, GROUP BY, KEYS, or non-all set queries: [{0}]
+ERR.015.012.0027 = Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in comparison: {0}.
+ValidationVisitor.expression_requires_name = Non-column expressions require a name in XMLATTRIBUTES, XMLFOREST, QUERYSTRING, or TEXTAGG with HEADER
+ValidationVisitor.invalid_lookup_key=Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used as LOOKUP key columns: {0}.
+ValidationVisitor.limit_not_valid_for_xml=The limit clause cannot be used on an XML document query.
+ValidationVisitor.translated_or=Translated user criteria must not contain OR criteria
+ValidationVisitor.union_insert = Select into is not allowed under a set operation: {0}.
+ValidationVisitor.multisource_insert = A multi-source table, {0}, cannot be used in an INSERT with query expression or SELECT INTO statement.
+ValidationVisitor.virtual_update_subquery = Subqueries are not allowed in the criteria for a virtual UPDATE/DELETE: {0}
+ValidationVisitor.invalid_encoding = Invalid encoding: {0}.
+ERR.015.012.0029 = INSERT, UPDATE, and DELETE not allowed on XML documents
+ERR.015.012.0030 = Commands used in stored procedure language not allowed on XML documents
+ERR.015.012.0031 = Queries against XML documents can not have a GROUP By clause
+ERR.015.012.0032 = Queries against XML documents can not have a HAVING clause
+ERR.015.012.0033 = Metadata does not allow updates on the group: {0}
+ERR.015.012.0034 = Queries involving UNIONs, INTERSECTs and EXCEPTs not allowed on XML documents
+ERR.015.012.0035 = Queries combined with the set operator {0} must have the same number of output elements.
+ERR.015.012.0037 = Invalid symbol: {0}. When an aggregate function is used in the SELECT clause and no GROUP BY clause is specified, the SELECT clause may contain only aggregate functions and constants.
+ERR.015.012.0038 = Invalid symbol: {0}. When a GROUP BY clause is used, all elements in the SELECT clause must be declared in the GROUP BY clause.
+ERR.015.012.0039 = Nested aggregate expressions are not allowed: {0}
+ERR.015.012.0041 = The aggregate function {0} cannot be used with non-numeric expressions: {1}
+AggregateValidationVisitor.non_comparable = The aggregate function {0} cannot be used with non-comparable expressions: {1}
+AggregateValidationVisitor.non_xml = The XMLAGG aggregate function {0} requires an expression of type XML: {1}
+AggregateValidationVisitor.non_boolean=The boolean aggregate functions ANY, SOME, EVERY require a boolean expression.
+AggregateValidationVisitor.invalid_distinct=The enhanced numeric aggregate functions STDDEV_POP, STDDEV_SAMP, VAR_POP, VAR_SAMP cannot have DISTINCT specified.
+ERR.015.012.0052 = The element [{0}] is in an INSERT but does not support updates.
+ERR.015.012.0053 = Element in the group {0}, for which value is not specified in the insert command is neither nullable nor has a default value: {1}
+ERR.015.012.0054 = Column variables do not reference columns on group "{0}": {1}
+ERR.015.012.0055 = Element {0} does not allow nulls.
+ERR.015.012.0058 = Left side of update expression may not be a variable or a reference to an external element: {0}
+ERR.015.012.0059 = Left side of update expression must be an element that supports update: {0}
+ERR.015.012.0060 = Element {0} does not allow nulls.
+ERR.015.012.0061 = Update values must be a constant expression.  The expression ''{0}'' cannot be evaluated to a constant.
+ERR.015.012.0062 = Elements cannot appear more than once in a SET or USING clause.  The following elements are duplicated: {0}
+ERR.015.012.0063 = Multiple failures occurred during validation:
+ERR.015.012.0064 = Validation succeeded
+ERR.015.012.0065 = Nested Loop can not use the same cursor name as that of its parent.
+ERR.015.012.0067 = No scalar subqueries are allowed in the SELECT with no FROM clause.
+ERR.015.012.0069 = INTO clause can not be used in XML query.
+
+# optimizer (004)
+ERR.015.004.0007= Can''t convert plan node of type {0}
+ERR.015.004.0009= Error finding connectorBindingID for command
+ERR.015.004.0010= Unknown group specified in OPTION MAKEDEP/MAKENOTDEP: {0}
+ERR.015.004.0012= Group has an access pattern which has not been met: group(s) {0}; access pattern(s) {1}
+ERR.015.004.0020= Error getting model for {0}
+ERR.015.004.0023= Error rewriting criteria: {0}
+ERR.015.004.0024= Unable to create a query plan that sends a criteria to \"{0}\".  This connection factory requires criteria set to true indicating that a query against this model requires criteria.  
+ERR.015.004.0029= Could not resolve group symbol {0}
+ERR.015.004.0035= The criteria {0} has elements from the root staging table and the document nodes which is not allowed.
+ERR.015.004.0037= No mapping node found named, ''{0}', in use of ''context''
+ERR.015.004.0046= The XML document element(s) {0} are not mapped to data and cannot be used in the criteria \"{1}\".
+ERR.015.004.0054= Could not parse query transformation for {0}: {1}
+ERR.015.004.0068= Context functions within the same conjunct refer to different contexts: {0}
+
+# processor (006)
+ERR.015.006.0001= XMLPlan toString couldn''t print entire Program.
+ERR.015.006.0034= Unexpected symbol type while updating tuple: {0}
+ERR.015.006.0037= Tuple source does not exist: {0}
+ERR.015.006.0039= Instructed to abort processing when recursion limit reached.
+ERR.015.006.0042= No xml schema to validate document against
+ERR.015.006.0048= Fatal Error: {0}
+ERR.015.006.0049= Error: {0}
+ERR.015.006.0051= Invalid direction for MoveDocInstruction: {0}
+ERR.015.006.0054= Instructed to abort processing as default of choice.
+
+# rewriter (009)
+ERR.015.009.0001= Error evaluating criteria: {0}
+ERR.015.009.0002= Error translating criteria on the user''s command, the criteria translated to {0} is not valid
+ERR.015.009.0003= Error simplifying mathematical expression: {0}
+
+
+SQLParser.Unknown_join_type=Unknown join type: {0}
+SQLParser.Aggregate_only_top_level=Aggregate expressions are allowed only as top level functions in the SELECT and HAVING clauses.
+SQLParser.Unknown_agg_func=Unknown aggregate function: {0}
+SQLParser.Invalid_func=Invalid function name: [{0}]
+SQLParser.Integer_parse=Unable to parse integer literal: {0}
+SQLParser.Float_parse=Unable to parse floating point literal: {0}
+SQLParser.Invalid_id=Invalid metadata ID format: [{0}]
+SQLParser.Invalid_alias=Invalid alias format: [{0}]
+SQLParser.Invalid_short_name=Invalid simple identifier format: [{0}]
+SQLParser.Invalid_char={0} value must be a single character: [{1}].
+SQLParser.expected_non_reserved=Expected non-reserved word {0}, but was {1}.
+SystemSource.Add_desc=Add two numbers
+SystemSource.Add_result_desc=Left operand + right operand
+SystemSource.Subtract_desc=Subtract two numbers
+SystemSource.Subtract_result_desc=Left operand - right operand
+SystemSource.Multiply_desc=Multiply two numbers
+SystemSource.Multiply_result_desc=Left operand * right operand
+SystemSource.Divide_desc=Divide two numbers
+SystemSource.Divide_result_desc=Left operand / right operand
+SystemSource.Ceiling_desc=Ceiling of number
+SystemSource.Exp_desc=e^number
+SystemSource.Floor_desc=Floor of number
+SystemSource.Log_desc=Log (base e) of number
+SystemSource.Log10_desc=Log (base 10) of number
+SystemSource.Acos_desc=Arccosine of number
+SystemSource.Asin_desc=Arcsine of number
+SystemSource.Atan_desc=Arctan of number
+SystemSource.Atan2_desc=Arctan of number1 / number2
+SystemSource.Cos_desc=Cosine of number
+SystemSource.Cot_desc=Cotangent of number
+SystemSource.Degrees_desc=Convert from radians to degrees
+SystemSource.Pi_desc=Constant value for pi
+SystemSource.Radians_desc=Convert from degrees to radians
+SystemSource.Sin_desc=Sine of number
+SystemSource.Tan_desc=Tangent of number
+SystemSource.Bitand_desc=Bitwise AND of two integers
+SystemSource.Bitand_result_desc=integer1 AND integer2
+SystemSource.Bitor_desc=Bitwise inclusive OR of two integers
+SystemSource.Bitor_result_desc=integer1 OR integer2
+SystemSource.Bitxor_desc=Bitwise exclusive OR (XOR) of two integers
+SystemSource.Bitxor_result_desc=integer1 XOR integer2
+SystemSource.Bitnot_desc=Bitwise inversion (NOT) of a 32-bit integer. Equivalent to XOR(integer, 0xFFFFFFFF)
+SystemSource.Bitnot_result_desc=32-bit inverted integer
+SystemSource.Curdate_desc=Current date
+SystemSource.Curtime_desc=Current time
+SystemSource.Now_desc=Current timestamp
+SystemSource.Dayname_result_d_desc=Day name for date
+SystemSource.Dayname_result_ts_desc=Day name for timestamp
+SystemSource.Dayofmonth_result_d_desc=Day of month for date (1 = 1st)
+SystemSource.Dayofmonth_result_ts_desc=Day of month for timestamp (1 = 1st)
+SystemSource.Dayofweek_result_d_desc=Day of week for date (1 = Sunday)
+SystemSource.Dayofweek_result_ts_desc=Day of week for timestamp (1 = Sunday)
+SystemSource.Dayofyear_result_d_desc=Day of year for date (1 = Jan 1st)
+SystemSource.Dayofyear_result_ts_desc=Day of year for timestamp (1 = Jan 1st)
+SystemSource.Month_result_d_desc=Month for date (1 = January)
+SystemSource.Month_result_ts_desc=Month for timestamp (1 = January)
+SystemSource.Monthname_result_d_desc=Month name for date
+SystemSource.Monthname_result_ts_desc=Month name for timestamp
+SystemSource.Week_result_d_desc=Week of year for date
+SystemSource.Week_result_ts_desc=Week of year for timestamp
+SystemSource.Year_result_d_desc=Year for date
+SystemSource.Year_result_ts_desc=Year for timestamp
+SystemSource.Hour_result_t_desc=Hour for time
+SystemSource.Hour_result_ts_desc=Hour for timestamp
+SystemSource.Minute_result_t_desc=Minute for time
+SystemSource.Minute_result_ts_desc=Minute for timestamp
+SystemSource.Second_result_t_desc=Second for time
+SystemSource.Second_result_ts_desc=Second for timestamp
+SystemSource.Quarter_result_d_desc=Quarter for date (1=Jan/Feb/Mar)
+SystemSource.Quarter_result_ts_desc=Quarter for timestamp (1=Jan/Feb/Mar)
+SystemSource.Length_result=Length of string
+SystemSource.Ucase_result=Upper case of string
+SystemSource.Lcase_result=Lower case of string
+SystemSource.Lower_result=Lower case of string
+SystemSource.Upper_result=Upper case of string
+SystemSource.UcaseClob_result=Upper case of clob
+SystemSource.LcaseClob_result=Lower case of clob
+SystemSource.LowerClob_result=Lower case of clob
+SystemSource.UpperClob_result=Upper case of clob
+SystemSource.Left_result=Left trimmed string
+SystemSource.Right_result=Right trimmed string
+SystemSource.Formattime_desc=Convert to string
+SystemSource.Formattime_result_desc=Converted time
+SystemSource.Formatdate_desc=Convert to string
+SystemSource.Formatdate_result_desc=Converted date
+SystemSource.Formattimestamp_desc=Convert to string
+SystemSource.Formattimestamp_result_desc=Converted timestamp
+SystemSource.Parsetime_desc=Convert string to time
+SystemSource.Parsetime_result_desc=Time converted
+SystemSource.Parsedate_desc=Convert string to date
+SystemSource.Parsedate_result_desc=Date converted
+SystemSource.Parsetimestamp_desc=Convert string to timestamp
+SystemSource.Parsetimestamp_result_desc=Timestamp converted
+SystemSource.Formatinteger_desc=Convert to Integer
+SystemSource.Formatinteger_result_desc=Integer formatted
+SystemSource.Formatlong_desc=Convert to Long
+SystemSource.Formatlong_result_desc=Long formatted
+SystemSource.Formatdouble_desc=Convert to Double
+SystemSource.Formatdouble_result_desc=Double formatted
+SystemSource.Formatfloat_desc=Convert to Float
+SystemSource.Formatfloat_result_desc=Float formatted
+SystemSource.Formatbiginteger_desc=Convert to Big integer
+SystemSource.Formatbiginteger_result_desc=Big integer formatted
+SystemSource.Formatbigdecimal_desc=Convert to Big decimal
+SystemSource.Formatbigdecimal_result_desc=Big decimal formatted
+SystemSource.Parseinteger_desc=Parse to Integer
+SystemSource.Parseinteger_result_desc=Integer parsed
+SystemSource.Parselong_desc=Parse to Long
+SystemSource.Parselong_result_desc=Long parsed
+SystemSource.Parsedouble_desc=Parse to Double
+SystemSource.Parsedouble_result_desc=Double parsed
+SystemSource.Parsefloat_desc=Parse to Float
+SystemSource.Parsefloat_result_desc=Float parsed
+SystemSource.Parsebiginteger_desc=Parse to Biginteger
+SystemSource.Parsebiginteger_result_desc=Biginteger parsed
+SystemSource.Parsebigdecimal_desc=parse to Bigdecimal
+SystemSource.Parsebigdecimal_result_desc=Bigdecimal parsed
+SystemSource.Arith_left_op=Left operand
+SystemSource.Arith_right_op=Right operand
+SystemSource.Abs_desc=Absolute value of number
+SystemSource.Abs_arg=Number
+SystemSource.Abs_result_desc=Absolute value of number
+SystemSource.Rand_desc=Random Number
+SystemSource.Rand_arg=Number
+SystemSource.Rand_result_desc=Generated Random Number
+SystemSource.Double_arg2=Number
+SystemSource.Atan_arg1=Number parameter1 
+SystemSource.Atan_arg2=Number parameter2 
+SystemSource.Mod_desc=Modulus of two numbers
+SystemSource.Mod_result_desc=Left operand mod right operand
+SystemSource.Power_desc=Raise base to power
+SystemSource.Power_arg1=Base
+SystemSource.Power_arg2=Power
+SystemSource.Power_result_desc=Base ^ Power
+SystemSource.Round_desc=Round number to specified places
+SystemSource.Round_arg1=Numbers
+SystemSource.Round_arg2=Places
+SystemSource.Round_result_desc=Number rounded to specified places
+SystemSource.Sign_desc=Sign of number: 1 if number>0, 0 if number==0, -1 if number<0
+SystemSource.Sign_arg1=Number
+SystemSource.Sign_result_desc=Sign of number
+SystemSource.Sqrt_desc=Square root of number
+SystemSource.Sqrt_arg1=Number
+SystemSource.Sqrt_result_desc=Square root of number
+SystemSource.Timestampadd_d_desc=Add count number of interval type to date
+SystemSource.Timestampadd_d_arg1=Interval type
+SystemSource.Timestampadd_d_arg2=Count number
+SystemSource.Timestampadd_d_arg3=Date type
+SystemSource.Timestampadd_d_result_desc=Returned modified date
+SystemSource.Timestampadd_t_desc=Add count number of interval type to time
+SystemSource.Timestampadd_t_arg1=Interval type
+SystemSource.Timestampadd_t_arg2=Count number
+SystemSource.Timestampadd_t_arg3=Time type
+SystemSource.Timestampadd_t_result_desc=Returned modified time
+SystemSource.Timestampadd_ts_desc=Add count number of interval type to timestamp
+SystemSource.Timestampadd_ts_arg1=Interval type
+SystemSource.Timestampadd_ts_arg2=Count number
+SystemSource.Timestampadd_ts_arg3=Timestamp type
+SystemSource.Timestampadd_ts_result=Returned modified timestamp
+SystemSource.Timestampdiff_ts_desc=Calculate estimated number of intervals between start and end timestamp
+SystemSource.Timestampdiff_ts_arg1=Interval type
+SystemSource.Timestampdiff_ts_arg2=Start timestamp
+SystemSource.Timestampdiff_ts_arg3=End timestamp
+SystemSource.Timestampdiff_ts_result_desc=Returns estimated number of intervals between start and end timestamp
+SystemSource.TimestampCreate_desc=Create timestamp from a date and a time
+SystemSource.TimestampCreate_arg1=Date
+SystemSource.TimestampCreate_arg2=Time
+SystemSource.TimestampCreate_result_desc=Timestamp built from date and time
+SystemSource.Stringfunc_arg1=String
+SystemSource.Clobfunc_arg1=Clob
+SystemSource.Concat_desc=Concatenate left and right strings
+SystemSource.Concat_arg1=Left string
+SystemSource.Concat_arg2=Right string
+SystemSource.Concat_result_desc=Concatenated strings
+SystemSource.Concatop_desc=Concatenate left and right strings
+SystemSource.Concatop_arg1=Left string
+SystemSource.Concatop_arg2=Right string
+SystemSource.Concatop_result_desc=Concatenated strings
+SystemSource.Substring_desc=Substring of string, starting at index, of length
+SystemSource.Substring_arg1=String
+SystemSource.Substring_arg2=Starting index
+SystemSource.Substring_arg3=Length of substring
+SystemSource.Substring_result=Substring
+SystemSource.Susbstring2_desc=Substring of string, starting at index, to end of string
+SystemSource.Substring2_arg1=String
+SystemSource.Substring2_arg2=Starting index
+SystemSource.Substring2_result=Substring
+SystemSource.Left_desc=First length characters of string
+SystemSource.Left_arg1=String
+SystemSource.Left_arg2=Length of substring
+SystemSource.Left2_result=First length characters of string
+SystemSource.Right_desc=Last length characters of string
+SystemSource.Right_arg1=String
+SystemSource.Right_arg2=Length of substring
+SystemSource.Right2_result=Last length characters of string
+SystemSource.Locate_desc=Find index of substring in string starting at index
+SystemSource.Locate_arg1=Substring to find
+SystemSource.Locate_arg2=String
+SystemSource.Locate_arg3=Starting index
+SystemSource.Locate_result=Index of substring or -1 if not found
+SystemSource.Locate2_desc=Find index of substring in string
+SystemSource.Locate2_arg1=Substring to find
+SystemSource.Locate2_arg2=String
+SystemSource.Locate2_result=Index of substring or -1 if not found
+SystemSource.Replace_desc=Replace any substring in string with replacement
+SystemSource.Replace_arg1=String
+SystemSource.Replace_arg2=Substring to match
+SystemSource.Replace_arg3=Replacement string
+SystemSource.Replace_result=String with replacements
+SystemSource.Repeat_desc=Repeat string with count times
+SystemSource.Repeat_arg1=String
+SystemSource.Repeat_arg2=Count times to repeat
+SystemSource.Repeat_result=String repeated with count times
+SystemSource.Space_desc=Repeat space count times
+SystemSource.Space_arg1=Number of times to repeat
+SystemSource.Space_result=Space repeated count times
+SystemSource.Insert_desc=Insert string2 into string1 by deleting length characters at start and inserting string2
+SystemSource.Insert_arg1=Initial string
+SystemSource.Insert_arg2=Starting position
+SystemSource.Insert_arg3=Number of characters to delete at start
+SystemSource.Insert_arg4=String to insert
+SystemSource.Insert_result=Inserted string
+SystemSource.Ascii_desc=Takes a character and returns the ASCII or unicode integer representation
+SystemSource.Ascii_arg1=String
+SystemSource.Ascii_result=Character value
+SystemSource.Ascii2_desc=Takes a character and returns the ASCII or unicode integer representation
+SystemSource.Ascii2_arg1=Character
+SystemSource.Ascii2_result=Character value
+SystemSource.Chr_desc=Takes a unicode or ASCII value and returns the character representation
+SystemSource.Chr_arg1=Code value
+SystemSource.Chr_result=Character representation
+SystemSource.Char_desc=Takes a unicode or ASCII value and returns the character representation
+SystemSource.Char_arg1=Code value
+SystemSource.Char_result=Character representation
+SystemSource.Initcap_desc=Capitalizes each word (each letter after whitespace)
+SystemSource.Initcap_arg1=Input string
+SystemSource.Initcap_result=Result string
+SystemSource.Lpad_desc=Pad the input string on the left to length
+SystemSource.Lpad_arg1=String
+SystemSource.Lpad_arg2=Padded length
+SystemSource.Lpad_result=Padded string
+SystemSource.Lpad3_desc=Pad the input string on the left to length with pad character
+SystemSource.Lpad3_arg1=String
+SystemSource.Lpad3_arg2=Padded length
+SystemSource.Lpad3_arg3=Pad character
+SystemSource.Lpad3_result=Padded string
+SystemSource.Rpad1_desc=Pad the input string on the right to length
+SystemSource.Rpad1_arg1=String
+SystemSource.Rpad1_arg2=Padded length
+SystemSource.Rpad1_result=Padded string
+SystemSource.Rpad3_desc=Pad the input string on the right to length with pad character
+SystemSource.Rpad3_arg1=String
+SystemSource.Rpad3_arg2=Padded length
+SystemSource.Rpad3_arg3=Pad character
+SystemSource.Rpad3_result=Padded string
+SystemSource.Translate_desc=Translate the input string by converting characters in the source string to characters in the destination string
+SystemSource.Translate_arg1=String
+SystemSource.Translate_arg2=Source string
+SystemSource.Translate_arg3=Destination string
+SystemSource.Translate_result=Translated string
+SystemSource.Convert_arg1=Source value
+SystemSource.Convert_arg2=Target type
+SystemSource.Convert_result=Converted value
+SystemSource.Context_desc=Evaluate XML expression in the context of a different mapping level
+SystemSource.Context_arg1=XML context tag
+SystemSource.Context_arg2=XML element
+SystemSource.Context_result=Expression in higher context
+SystemSource.Rowlimit_desc=Limit the number of rows from an XML mapping class
+SystemSource.RowlimitException_desc=Limit the number of rows from an XML mapping class, throw Exception if passed
+SystemSource.Rowlimit_arg1=XML tag in the scope of a mapping class
+SystemSource.Rowlimit_result=Number of rows to be limited to
+SystemSource.Decode1_desc=Map the input value to a comma-separated list of allowed output values
+SystemSource.Decode1_arg1=Input column for decode
+SystemSource.Decode1_arg2=The comma delimited String that represents the mapping between input column value and output values.
+SystemSource.Decode1_result=The decoded value from the decode string.
+SystemSource.Decode2_desc=Map the input value to a delimiter-separated list of allowed output values
+SystemSource.Decode2_arg1=Input column for decode
+SystemSource.Decode2_arg2=The comma delimited String that represents the mapping between input column value and output values.
+SystemSource.Decode2_arg3=Decode String delimiter character(s)
+SystemSource.Decode2_result=The decoded value from the decode string.
+SystemSource.Lookup_desc=Look up a value in a cached code table
+SystemSource.Lookup_arg1=Full group name of code table
+SystemSource.Lookup_arg2=Short name of return element in code table
+SystemSource.Lookup_arg3=Short name of key element in code table
+SystemSource.Lookup_arg4=Key value to lookup
+SystemSource.Lookup_result=Return value for key as specified in code table
+SystemSource.User_desc=Get current user name 
+SystemSource.User_result=Return user name
+SystemSource.current_database_desc=Get current database name
+current_database_result=Returns the catalog name
+SystemSource.Env_desc=Get the value of an environment variable 
+SystemSource.Env_varname=Name of the environment variable
+SystemSource.Env_result=Return the string value of the environment variable
+SystemSource.Nvl_desc=Specifies a value to use instead if the input value is null
+SystemSource.Nvl_arg1=Value to check
+SystemSource.Nvl_arg2=Returned if value is null
+SystemSource.Nvl_result=Value or valueIfNull if value is null
+SystemSource.Ifnull_desc=Specifies a value to use instead if the input value is null
+SystemSource.Ifnull_arg1=Value to check
+SystemSource.Ifnull_arg2=Returned if value is null
+SystemSource.Ifnull_result=Value or valueIfNull if value is null
+SystemSource.Formattime_arg1=Time input
+SystemSource.Formattime_arg2=Time format
+SystemSource.Formatdate_arg1=Date input
+SystemSource.Formatdate_arg2=Date format
+SystemSource.Formattimestamp_arg1=Timestamp input
+SystemSource.Formattimestamp_arg2=Timestamp format
+SystemSource.Parsetime_arg1=String input
+SystemSource.Parsetime_arg2=Time format
+SystemSource.Parsedate_arg1=String input
+SystemSource.Parsedate_arg2=Date format
+SystemSource.Parsetimestamp_arg1=String input
+SystemSource.Parsetimestamp_arg2=Timestamp format
+SystemSource.Formatnumber_arg1=String input
+SystemSource.Formatnumber_arg2=Number format
+SystemSource.Parsenumber_arg1=String input
+SystemSource.Parsenumber_arg2=Parse format
+SystemSource.Bitfunc_arg1=Integer parameter
+SystemSource.Bitfunc2_arg1=First integer
+SystemSource.Bitfunc2_arg2=Second integer
+SystemSource.Convert_desc=Convert from {0} to target type
+SystemSource.xpathvalue_description=Retrieve the first match content for an XPath statement
+SystemSource.xpath_param1=Source document
+SystemSource.xpath_param2=XPath expression
+SystemSource.xpathvalue_result=Single result
+SystemSource.xsltransform_description=Transform the document with the given stylesheet. 
+SystemSource.xsltransform_param1=Source document
+SystemSource.xsltransform_param2=XSL stylesheet
+SystemSource.xsltransform_result=Clob result
+SystemSource.xmlconcat_description=Concat XML types. 
+SystemSource.xmlconcat_param1=First element
+SystemSource.xmlcomment_description=Create an XML comment. 
+SystemSource.xmlconcat_param1=String comment
+SystemSource.xmlconcat_result=XML result
+SystemSource.xmlpi_description=Create an XML processing instruction. 
+SystemSource.xmlpi_param1=Target
+SystemSource.xmlpi_param2=Content
+SystemSource.xmlpi_result=XML result
+SystemSource.jsonToXml_description=Create an XML document representing the given JSON. 
+SystemSource.jsonToXml_param1=Root element name
+SystemSource.jsonToXml_param2=JSON
+SystemSource.jsonToXml_result=XML result
+SystemSource.modifyTimeZone_description=Modify the time zone of this timestamp by adding or subtracting time
+SystemSource.modifyTimeZone_param1=Timestamp
+SystemSource.modifyTimeZone_param2=Starting time zone
+SystemSource.modifyTimeZone_param3=Ending time zone
+SystemSource.modifyTimeZone_result=Original timestamp with time added or subtracted to give the equivalent time in a different time zone
+SystemSource.CommandPayload_desc0=Retrieve the command payload as a string
+SystemSource.CommandPayload_desc1=Retrieve a property from the command payload, passed as a Properties object
+SystemSource.CommandPayload_result=The property value from the command payload 
+SystemSource.CommandPayload_property=The property name
+SystemSource.hasRole_description=Determine if the caller has the given role
+SystemSource.hasRole_param1=Role type
+SystemSource.hasRole_param2=Role name
+SystemSource.hasRole_result=whether the caller is in the given role
+SystemSource.from_unixtime_description=Return the Unix timestamp (in seconds) as a Timestamp value 
+SystemSource.from_unixtime_param1=Unix timestamp (in seconds)
+SystemSource.from_unixtime_result=Timestamp value
+SystemSource.nullif_description=Equivalent to case when (param1 = param2) then null else param1 
+SystemSource.nullif_param1=First parameter
+SystemSource.nullif_result=null if the parameters are equivalent else param1
+SystemSource.coalesce_description=Returns the first non-null parameter
+SystemSource.coalesce_param1=parameter
+SystemSource.coalesce_result=The first non-null parameter
+SystemSource.encode_desc=Converts a Blob to the appropriate chars
+SystemSource.encode_arg1=Blob
+SystemSource.encode_arg2=char representation Clob
+SystemSource.encode_result=Clob char rep
+SystemSource.decode_desc=Converts a Clob to the appropriate bytes
+SystemSource.decode_arg1=Clob
+SystemSource.decode_arg2=The encoding
+SystemSource.decode_result=byte representation Blob
+SystemSource.session_id_desc=Returns the session id of the currently logged in user 
+SystemSource.session_id_result=Returns the session id of the currently logged in user
+TempMetadataAdapter.Element_____{0}_____not_found._1=Element ''{0}'' not found.
+TempMetadataAdapter.Group_____{0}_____not_found._1=Group ''{0}'' not found.
+ExpressionEvaluator.Must_push=Function {0} is marked in the function metadata as a function that must be evaluated at the source.
+ExpressionEvaluator.Eval_failed=Unable to evaluate {0}: {1}
+XMLSerialize.resolvingError=XMLSerialize is valid only for XML expressions: {0}
+Evaluator.xmlserialize=XMLSerialize: data exception - not an xml document
+Evaluator.xmlquery=Error evaluating XMLQuery: {0}
+ExecResolver.Param_convert_fail=Unable to convert procedural parameter of type {0} to expected type {1}
+ExecResolver.return_expected=Procedure {0} does not have a return value.
+ExecResolver.out_type_mismatch=OUT/RETURN parameter {0} with type {1} cannot be converted to {2}
+DynamicCommandResolver.SQL_String=Expected dynamic command sql to be of type STRING instead of type {0}.
+UnionQueryResolver.type_conversion=The Expression {0} used in a nested UNION ORDER BY clause cannot be implicitly converted from type {1} to type {2}.
+ValidationVisitor.select_into_no_implicit_conversion=There is no implicit conversion between the source element type ({0}) and the target element type ({1}) at position {2} of the query: {3}
+ValidationVisitor.excpet_intersect_all=EXCEPT ALL and INTERSECT ALL are currently unsupported
+ValidationVisitor.element_updates_not_allowed=Metadata does not allow updates on the element: {0}
+ValidationVisitor.invalid_batch_command=Only INSERT, UPDATE, DELETE, and SELECT ... INTO statements are allowed within a batch.
+ValidationVisitor.badoffset2=The row offset in the LIMIT clause must be >= 0
+ValidationVisitor.badlimit2=The row limit in the LIMIT clause must be >= 0
+ValidationVisitor.invalid_scalar_group_reference=Cannot reference a scalar group as a table: {0}
+ValidationVisitor.select_into_wrong_elements=Wrong number of elements being SELECTed INTO the target table. Expected {0} elements, but was {1}.
+SimpleQueryResolver.Query_was_redirected_to_Mat_table=The query against {0} was redirected to the materialization table {1}.
+SimpleQueryResolver.ambiguous_all_in_group=The symbol {0} refers to more than one group defined in the FROM clause.
+SimpleQueryResolver.Proc_Relational_Name_conflict=Cannot access procedure {0} using table semantics since the parameter and result set column names are not all unique.
+QueryResolver.invalid_xpath=Invalid xpath value: {0}
+ResolveVariablesVisitor.reserved_word_for_temporary_used=Cursor names cannot begin with "#" as that indicates the name of a temporary table: {0}.
+SimpleQueryResolver.materialized_table_not_used=The query against {0} did not use materialization table {1} due to the use of OPTION NOCACHE.
+SimpleQueryResolver.cache_hint_used=Loading materialized view {1} for view {0} using cache hint {2}.
+SimpleQueryResolver.procedure_cache_used=Procedure caching will be used for {0}.
+SimpleQueryResolver.procedure_cache_not_usable=Procedure caching will not be used for {0} since the result set cache is disabled or the results/parameters cannot be cached.
+SimpleQueryResolver.procedure_cache_not_used=Procedure caching will not be used for {0} due to the use of OPTION NOCACHE.
+ValidationVisitor.groupby_subquery=Expressions used in a GROUP BY cannot be constant and must not contain subqueries: "{0}".
+ValidationVisitor.Procedure_should_have_query=Procedure must execute at least one command to define the procedure result set.
+ValidationVisitor.Procedure_has_group_self_reference=Procedure cannot have a Group reference to itself.
+ExpressionEvaluator.Expected_props_for_payload_function=Unable to evaluate {0}: expected Properties for command payload but got object of type {1}
+ValidationVisitor.The_rowlimit_function_cannot_be_used_in_a_non-XML_command=The ''rowlimit'' and ''rowlimitexception'' functions cannot be used in a non-XML command
+ValidationVisitor.The_context_function_cannot_be_used_in_a_non-XML_command=The ''context'' function cannot be used in a non-XML command
+ValidationVisitor.0=The ''rowlimit'' and ''rowlimitexception'' functions cannot be nested within other functions.
+ValidationVisitor.1=The ''rowlimit'' and ''rowlimitexception'' functions operand must be a constant nonnegative integer.
+ValidationVisitor.2=The ''rowlimit'' and ''rowlimitexception'' functions arg must be an XML node symbol
+ValidationVisitor.3=''Rowlimit'' and ''rowlimitexception'' functions can only be used within a compare criteria which is entirely a single conjunct.
+ValidationVisitor.Context_function_nested=Context functions cannot be nested
+ERR.015.004.0036= First argument in ''context'' must be the name of a node in the XML document model.  Found Object {0} of Class {1}
+ExecResolver.invalid_named_params=Invalid param name(s): {0}.  Name(s) of params without explicit values: {1}  
+ExecResolver.duplicate_named_params=Duplicate named param ''{0}''
+ResolverUtil.required_param=Required parameter ''{0}'' has no value was set or is an invalid parameter.
+ResolverUtil.duplicateName=Cannot create group ''{0}'' with multiple columns named ''{1}''
+ResolverUtil.error_converting_value_type=Exception converting value {0} of type {1} to expected type {2}
+ResolverUtil.setquery_order_expression=ORDER BY expression ''{0}'' cannot be used with a set query.
+ResolverUtil.invalid_unrelated=Unrelated order by column {0} cannot be used in a SET query, with SELECT DISTINCT, or GROUP BY
+XMLQueryResolver.xml_only_valid_alone=If any symbol in SELECT clause is ''xml'' or group.''xml'' , then no other element is allowed.
+ResolveVariablesVisitor.datatype_for_the_expression_not_resolvable=The datatype for the expression was not resolvable.
+TempTableResolver.unqualified_name_required=Cannot create temporary table "{0}". Local temporary tables must be created with unqualified names.
+TempTableResolver.table_already_exists=Cannot create temporary table "{0}". A table with the same name already exists.
+ValidationVisitor.drop_of_nontemptable=Cannot drop a non temporary table "{0}".							
+ValidationVisitor.orderby_expression_xml=XML queries cannot order by an expression.
+ValidationVisitor.text_table_invalid_width=For a fixed width text table, all columns must have width set.
+ValidationVisitor.text_table_width=Fixed width text tables should not have DELIMITER, QUOTE, ESCAPE, or HEADER specified.
+ValidationVisitor.text_table_negative=Text table WIDTH, HEADER, or SKIP values must not be negative. 
+ValidationVisitor.text_table_delimiter=Text DELIMITER cannot be the same as the QUOTE or ESCAPE characters.
+ValidationVisitor.text_table_newline=Text DELIMITER, QUOTE, and ESCAPE characters cannot be the new line character.
+ValidationVisitor.xml_namespaces=At most only one NO DEFAULT or DEFAULT namespace may be specified.
+ValidationVisitor.xml_namespaces_reserved=The namespaces xmlns and xml are reserved.
+ValidationVisitor.xml_namespaces_null_uri=The null uri, or empty string, is not allowed as the uri value.
+ValidationVisitor.xml_attributes_reserved=The namespace xmlns is reserved.
+ValidationVisitor.xml_content_type=The expression "{0}" is of OBJECT or BLOB type, which cannot be used as an XML or TEXT content value.
+ValidationVisitor.xml_invalid_qname=The qname "{0}" is invalid.
+ValidationVisitor.context_item_type=XMLTABLE or XMLQUERY PASSING context item must be an XML value.
+ValidationVisitor.passing_requires_name=XMLTABLE or XMLQUERY PASSING clause can only contain at most 1 unnamed item.
+ValidationVisitor.duplicate_passing=XMLTABLE or XMLQUERY PASSING clause duplicate item name "{0}".
+ValidationVisitor.one_ordinal=Only one FOR ORDINALITY column is allowed for an XMLTABLE.
+ValidationVisitor.invalid_default=XMLTABLE DEFAULT expression is invalid: "{0}"
+ValidationVisitor.context_required=The XQuery requires a context item, but none exists in the PASSING clause.
+ValidationVisitor.xmlserialize_type=XMLSERIALIZE expects a STRING, CLOB, or BLOB value.
+ValidationVisitor.invalid_encoding=Encoding {0} is not valid.
+ValidationVisitor.subquery_insert=SELECT INTO should not be used in a subquery.
+UpdateProcedureResolver.only_variables=Element symbol "{0}" cannot be assigned a value.  Only declared VARIABLES can be assigned values.
+MappingLoader.unknown_node_type=Unknown Node Type "{0}" being loaded by the XML mapping document.
+MappingLoader.invalid_criteria_node=Invalid criteria node found; A criteria node must have criteria specified or it must be a default node.
+WrongTypeChild=Wrong type of child node is being added.
+NoCriteria=Failed to add the node, because Criteria nodes must have "criteria" value set on them, or they need to be the default node.
+root_cannotbe_null=Root node assigned to a document can be null.
+invalid_recurive_node= Found recursive node {0} without recursive root node.
+SaxonXQueryExpression.bad_xquery=Failed to evaluate XQuery expression; Please check the query and correct errors in syntax or usage. 
+SaxonXQueryExpression.compile_failed=Could not compile XQuery; Please check the query for syntax or usage errors.
+SaxonXQueryExpression.invalid_path=Column "{0}" has an invalid path expression: {1} 
+SaxonXQueryExpression.bad_context=Error building Source for context item.
+MappingLoader.invalidName=Null or blank name found in the Mapping Document, Must have valid name. Re-build the VDB
+MatchCriteria.invalid_escape=Invalid escape sequence "{0}" with escape character "{1}"
+QueryUtil.wrong_number_of_values=The number of bound values ''{0}'' does not match the number of parameters ''{1}'' in the prepared statement.
+QueryUtil.Error_executing_conversion_function_to_convert_value=Error converting parameter number {0} with value "{1}" to expected type {2}.
+InsertResolver.cant_convert_query_type=Cannot convert insert query expression projected symbol ''{0}'' of type {1} to insert column ''{2}'' of type {3}
+SetClause.resolvingError=Cannot set symbol ''{1}'' with expected type {2} to expression ''{0}''
+NewCalculateCostUtil.badCost=Unexpected format encountered for max or min value
+
+WorkerPool.Max_thread=Reached maximum thread count "{0}" for worker pool "{1}" with a queue size of "{2}".
+WorkerPool.uncaughtException=Uncaught exception processing work
+
+
+TempTable.duplicate_key=Duplicate key
+ValidationVisitor.group_in_both_dep=Table specified in both dependent and independent queries '{0}'
+XMLQuery.resolvingError=Failed to resolve the query '{0}'
+SQLParser.non_position_constant=Invalid order by at {0} 
+
+
+QueryRewriter.infinite_while=Infinite loop detected, procedure will not be executed.
+
+BatchedUpdatePlanner.unrecognized_command=The batch contained an unrecognized command: {0}
+ProcedurePlanner.bad_stmt=Error while planning update procedure, unknown statement type encountered: {0}
+RulePushSelectCriteria.Error_getting_modelID=Error getting modelID
+XMLPlanner.no_uri=Cannot find namespace URI for namespace {0} of element {1}
+
+XMLPlanner.The_XML_document_element_{0}_is_not_mapped_to_data_and_cannot_be_used_in_the_ORDER_BY_clause__{1}_1=The XML document element {0} is not mapped to data and cannot be used in the ORDER BY clause: {1}
+XMLPlanner.The_rowlimit_parameter_{0}_is_not_in_the_scope_of_any_mapping_class=The ''rowlimit'' or ''rowlimitexception'' function parameter ''{0}'' is not an XML node within the scope of any mapping class.
+XMLPlanner.Criteria_{0}_contains_conflicting_row_limits=The criteria ''{0}'' contains conflicting row limits for an XML mapping class.
+AccessNode.rewrite_failed=Failed to rewrite the command: {0}
+BatchedUpdateNode.unexpected_end_of_batch=Unexpectedly reached the end of the batched update counts at {0}, expected {1}.
+row_limit_passed=The row limit {0} has been exceeded for XML mapping class {1}.
+AddNodeInstruction.element__1=element
+AddNodeInstruction.Unable_to_add_xml_{0}_{1},_namespace_{2},_namespace_declarations_{3}_3=Unable to add xml {0} {1}, namespace {2}, namespace declarations {3}
+QueryProcessor.request_cancelled=The request {0} has been cancelled.
+VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state=INPUT variables used in the expression should all have same CHANGING state: {0}
+
+ExecDynamicSqlInstruction.0=Evaluated dynamic SQL expression value was null.
+ExecDynamicSqlInstruction.3=There is a recursive invocation of group ''{0}''. Please correct the SQL.
+ExecDynamicSqlInstruction.4=The dynamic sql string contains an incorrect number of elements.
+ExecDynamicSqlInstruction.6=The datatype ''{0}'' for element ''{1}'' in the dynamic SQL cannot be implicitly converted to ''{2}''.
+ExecDynamicSqlInstruction.couldnt_execute=Couldn''t execute the dynamic SQL command "{0}" with the SQL statement "{1}" due to: {2}
+
+RulePlanJoins.cantSatisfy=Join region with unsatisfied access patterns cannot be satisfied by the join criteria, Access patterns: {0} 
+TempTableStore.table_exist_error=Temporary table "{0}" already exists.
+TempTableStore.table_doesnt_exist_error=Temporary table "{0}" does not exist.
+
+XMLQueryPlanner.cannot_plan=Cannot create a query for MappingClass with user criteria {0}
+CriteriaPlanner.staging_context=Staging table criteria cannot contian context functions
+CriteriaPlanner.multiple_staging=Staging table criteria {0} was not specified against a single staging table
+CriteriaPlanner.invalid_context=Element {0} is not in the scope of the context {1}
+CriteriaPlanner.invalid_element=Element {0} is not a valid data node
+results_not_found=Results for the mapping class {0} are not found; 
+RulePlanProcedures.no_values=No valid criteria specified for procedure parameter {0}
+ProcedurePlan.nonNullableParam=The procedure parameter is not nullable, but is set to null: {0}
+ 
+FileStoreageManager.error_creating=Error creating {0}
+FileStoreageManager.error_reading=Error reading {0}
+FileStoreageManager.no_directory=No directory specified for the file storage manager.
+FileStoreageManager.not_a_directory={0} is not a valid storage manager directory.
+FileStoreageManager.space_exhausted=Max buffer space of {0} bytes has been exceed.  The current operation will be aborted.
+
+TextTableNode.no_value=No value found for column \"{0}\" in the row ending on text line {1} in {2}.
+TextTableNode.conversion_error=Could not convert value for column \"{0}\" in the row ending on text line {1} in {2}.
+TextTableNode.header_missing=HEADER entry missing for column name \"{0}\" in {1}. 
+TextTableNode.unclosed=Text parse error: Unclosed qualifier at end of text in {0}.
+TextTableNode.character_not_allowed=Text parse error: Non-whitespace character found between the qualifier and the delimiter in text line {0} in {1}.
+TextTableNode.unknown_escape=Text parse error: Unknown escape sequence \\{0} in text line {1} in {2}.
+TextTableNode.invalid_width=Text parse error: Fixed width line width {0} is smaller than the expected {1} on text line {2} in {3}.
+
+XMLTableNode.error=Error evaluating XQuery row context for XMLTable: {0}
+XMLTableNode.path_error=Error evaluating XMLTable column path expression for column: {0}
+XMLTableName.multi_value=Unexpected multi-valued result was returned for XMLTable column "{0}".  Path expressions for non-XML type columns should return at most a single result.
+
+TempTableDataManager.failed_load=Failed to load materialized view table {0}.
+TempTableDataManager.loaded=Loaded materialized view table {0} with row count {1}.
+TempTableDataManager.loading=Loading materialized view table {0}
+TempTableDataManager.not_implicit_matview={0} does not target an internal materialized view.
+TempTableDataManager.row_refresh_pk=Materialized view {0} cannot have a row refreshed since there is no primary key.
+TempTableDataManager.row_refresh_composite=Materialized view {0} cannot have a row refreshed because it uses a composite key.
+TempTableDataManager.row_refresh_updatable=Materialized view {0} cannot have a row refreshed because it's cache hint did not specify \"updatable\".
+TempTableDataManager.row_refresh=Refreshing row {1} for materialized view {0}.
+CriteriaPlanner.no_context=No root node found.
+
+BasicInterceptor.ProcessTree_for__4=ProcessTree for
+
+
+ConnectorManager.not_in_valid_state=Connector is not in OPEN state
+
+ConnectorManagerImpl.Initializing_connector=Initializing connector {0}
+Cancel_request_failed=AtomicRequest {0} failed to cancel.
+
+ConnectorWorker.MaxResultRowsExceed=The number of result rows has exceeded the maximum result rows "{0}"
+ConnectorWorker.zero_size_non_last_batch=Connector returned a 0 row non-last batch: {0}.
+ConnectorWorker.process_failed=Connector worker process failed for atomic-request={0}
+ConnectorWorker.ConnectorWorker_result_set_unexpected_columns=Could not process stored procedure results for {0}.  Expected {1} result set columns, but was {2}.  Please update your models to allow for stored procedure results batching.
+
+
+DataTierManager.could_not_obtain_connector_binding=Could not obtain connection factory for model {0} in VDB name= {1}, version {2}
+
+
+DQPCore.Unable_to_load_metadata_for_VDB_name__{0},_version__{1}=Unable to load metadata for VDB name= {0}, version= {1}
+DQPCore.Unknown_query_metadata_exception_while_registering_query__{0}.=Unknown query metadata exception while registering query: {0}.
+DQPCore.Clearing_prepared_plan_cache=Clearing prepared plan cache
+DQPCore.The_request_has_been_closed.=The request {0} has been closed.
+DQPCore.The_atomic_request_has_been_cancelled=The atomic request {0} has been canceled.
+DQPCore.failed_to_cancel=Failed to Cancel request, as request already finished processing
+
+ProcessWorker.failed_rollback=Failed to properly rollback autowrap transaction properly
+ProcessWorker.error=Unexpected exception for request {0}
+ProcessWorker.processing_error=Processing exception ''{0}'' for request {1}.  Exception type {2} thrown from {3}. Enable more detailed logging to see the entire stacktrace.
+
+
+# #query (018.005)
+ERR.018.005.0095 = User <{0}> is not entitled to action <{1}> for 1 or more of the groups/elements/procedures.
+
+# services (003)
+
+Request.Invalid_character_in_query=Bind variables (represented as "?") were found but are allowed only in prepared or callable statements.
+Request.no_result_set=The query does not return an update count.
+Request.result_set=The query does not return a result set.
+
+ProcessWorker.wrongdata=Wrong type of data found or no data found; expecting streamable object from the buffer manager.
+ProcessWorker.LobError=An error occurred during streaming of Lob Chunks to Client.
+
+TransactionServer.existing_transaction=Client thread already involved in a transaction. Transaction nesting is not supported. The current transaction must be completed first.
+TransactionServer.no_transaction=No transaction found for client {0}.
+TransactionServer.concurrent_transaction=Concurrent enlistment in global transaction {0} is not supported.
+TransactionServer.no_global_transaction=Expected an existing global transaction {0} but there was none for client {1}
+TransactionServer.unknown_flags=Unknown flags
+TransactionServer.no_global_transaction=No global transaction found for {0}.
+TransactionServer.wrong_transaction=Client is not currently enlisted in transaction {0}.
+TransactionServer.resume_failed=Cannot resume, transaction {0} was not suspended by client {1}.
+TransactionServer.existing_global_transaction=Global transaction {0} already exists.
+TransactionServer.suspended_exist=Suspended work still exists on transaction {0}.
+
+TransformationMetadata.does_not_exist._1=does not exist.
+TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1=Error trying to read virtual document {0}, with body \n{1}
+TransformationMetadata.Unknown_support_constant___12=Unknown support constant: 
+TransformationMetadata.QueryPlan_could_not_be_found_for_physical_group__6=QueryPlan could not be found for physical group 
+TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8=InsertPlan could not be found for physical group 
+TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10=InsertPlan could not be found for physical group 
+TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12=DeletePlan could not be found for physical group 
+TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1=Error trying to read schemas for the document/table : 
+TransformationMetadata.Invalid_type=Invalid type: {0}.
+TransformationMetadata.does_not_exist._1=does not exist.
+TransformationMetadata.0={0} ambiguous, more than one entity matching the same name
+TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1=Error trying to read virtual document {0}, with body \n{1}
+TransformationMetadata.Unknown_support_constant___12=Unknown support constant: 
+TransformationMetadata.QueryPlan_could_not_be_found_for_physical_group__6=QueryPlan could not be found for physical group 
+TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8=InsertPlan could not be found for physical group 
+TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10=InsertPlan could not be found for physical group 
+TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12=DeletePlan could not be found for physical group 
+TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1=Error trying to read schemas for the document/table : 
+TransformationMetadata.Invalid_type=Invalid type: {0}.
+
+CachedFinder.no_connector_found=No connector with jndi-name {0} found for Model {1} with source name {2} 
+translator_not_found=Translator {0} not accessible.
+datasource_not_found=Data Source {0} not accessible.
+
+RequestWorkItem.cache_nondeterministic=Caching command "{0}" at a session level, but less deterministic functions were evaluated. 
+not_found_cache=Results not found in cache
+failed_to_unwrap_connection=Failed to unwrap the source connection.
+connection_factory_not_found=Failed to the Connection Factory with JNDI name {0}. Please check the name for spelling or deploy the Connection Factory with specified name. 
+
+RelationalPlanner.nonpushdown_command=Source command "{0}" contains non-pushdown constructs. 
+
+Translate.error=Cannot translate criteria "{0}", it is not matched by selector "{1}"
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java
===================================================================
--- branches/7.2.x/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,78 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.dqp.internal.process;
-
-import java.util.Map;
-
-import org.mockito.Mockito;
-import org.teiid.adminapi.DataPolicy;
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.core.util.UnitTestUtil;
-
-import junit.framework.TestCase;
-
-
-public class TestDQPWorkContext extends TestCase {
-
-	/**
-	 * Constructor for TestRequestMessage.
-	 * 
-	 * @param name
-	 */
-	public TestDQPWorkContext(String name) {
-		super(name);
-	}
-
-	public static DQPWorkContext example() {
-		DQPWorkContext message = new DQPWorkContext();
-		message.getSession().setVDBName("vdbName"); //$NON-NLS-1$
-		message.getSession().setVDBVersion(1); 
-		message.getSession().setApplicationName("querybuilder"); //$NON-NLS-1$
-		message.getSession().setSessionId(String.valueOf(5));
-		message.getSession().setUserName("userName"); //$NON-NLS-1$
-		return message;
-	}
-
-	public void testSerialize() throws Exception {
-		DQPWorkContext copy = UnitTestUtil.helpSerialize(example());
-
-		assertEquals("5", copy.getSessionId()); //$NON-NLS-1$
-		assertEquals("userName", copy.getUserName()); //$NON-NLS-1$
-		assertEquals("vdbName", copy.getVdbName()); //$NON-NLS-1$
-		assertEquals(1, copy.getVdbVersion());
-		assertEquals("querybuilder", copy.getAppName()); //$NON-NLS-1$
-	}
-
-	
-	public void testClearPolicies() {
-		DQPWorkContext message = new DQPWorkContext();
-		message.setSession(Mockito.mock(SessionMetadata.class));
-		Map<String, DataPolicy> map = message.getAllowedDataPolicies();
-		map.put("role", Mockito.mock(DataPolicy.class)); //$NON-NLS-1$
-		assertFalse(map.isEmpty());
-		
-		message.setSession(Mockito.mock(SessionMetadata.class));
-		map = message.getAllowedDataPolicies();
-		assertTrue(map.isEmpty());
-	}
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java (from rev 2707, branches/7.2.x/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,95 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.dqp.internal.process;
+
+import java.util.Map;
+
+import org.mockito.Mockito;
+import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.impl.DataPolicyMetadata;
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.core.util.UnitTestUtil;
+
+import junit.framework.TestCase;
+
+
+public class TestDQPWorkContext extends TestCase {
+
+	/**
+	 * Constructor for TestRequestMessage.
+	 * 
+	 * @param name
+	 */
+	public TestDQPWorkContext(String name) {
+		super(name);
+	}
+
+	public static DQPWorkContext example() {
+		DQPWorkContext message = new DQPWorkContext();
+		message.getSession().setVDBName("vdbName"); //$NON-NLS-1$
+		message.getSession().setVDBVersion(1); 
+		message.getSession().setApplicationName("querybuilder"); //$NON-NLS-1$
+		message.getSession().setSessionId(String.valueOf(5));
+		message.getSession().setUserName("userName"); //$NON-NLS-1$
+		return message;
+	}
+
+	public void testSerialize() throws Exception {
+		DQPWorkContext copy = UnitTestUtil.helpSerialize(example());
+
+		assertEquals("5", copy.getSessionId()); //$NON-NLS-1$
+		assertEquals("userName", copy.getUserName()); //$NON-NLS-1$
+		assertEquals("vdbName", copy.getVdbName()); //$NON-NLS-1$
+		assertEquals(1, copy.getVdbVersion());
+		assertEquals("querybuilder", copy.getAppName()); //$NON-NLS-1$
+	}
+
+	
+	public void testClearPolicies() {
+		DQPWorkContext message = new DQPWorkContext();
+		message.setSession(Mockito.mock(SessionMetadata.class));
+		Mockito.stub(message.getSession().getVdb()).toReturn(new VDBMetaData());
+		Map<String, DataPolicy> map = message.getAllowedDataPolicies();
+		map.put("role", Mockito.mock(DataPolicy.class)); //$NON-NLS-1$
+		assertFalse(map.isEmpty());
+		
+		message.setSession(Mockito.mock(SessionMetadata.class));
+		Mockito.stub(message.getSession().getVdb()).toReturn(new VDBMetaData());
+		map = message.getAllowedDataPolicies();
+		assertTrue(map.isEmpty());
+	}
+	
+	public void testAnyAuthenticated() {
+		DQPWorkContext message = new DQPWorkContext();
+		message.setSession(Mockito.mock(SessionMetadata.class));
+		VDBMetaData vdb = new VDBMetaData();
+		DataPolicyMetadata dpm = new DataPolicyMetadata();
+		dpm.setAnyAuthenticated(true);
+		vdb.addDataPolicy(dpm);
+		Mockito.stub(message.getSession().getVdb()).toReturn(vdb);
+		
+		Map<String, DataPolicy> map = message.getAllowedDataPolicies();
+		assertEquals(1, map.size());
+	}
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
===================================================================
--- branches/7.2.x/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,813 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.optimizer;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
-import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.optimizer.relational.rules.RuleChooseDependent;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.AccessNode;
-import org.teiid.query.processor.relational.DependentAccessNode;
-import org.teiid.query.processor.relational.RelationalNode;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-
-
-
-public class TestDependentJoins extends TestCase {
-    
-    static void checkDependentGroups(ProcessorPlan plan, String[] groups) {
-        if(! (plan instanceof RelationalPlan)) {
-            return;                
-        }
-                                
-        // Collect all the group names (uppercase) for all the dependent groups in the plan
-        Set depGroups = new HashSet();
-        getDependentGroups(((RelationalPlan)plan).getRootNode(), depGroups);
-
-        // Check that all the expected groups exist in depGroups
-        Set expectedGroups = new HashSet();
-        for(int i=0; i<groups.length; i++) {
-            expectedGroups.add(groups[i].toUpperCase());    
-        }        
-        
-        assertEquals("Expected groups were not made dependent", expectedGroups, depGroups);         //$NON-NLS-1$
-    }
-    
-    static void getDependentGroups(RelationalNode node, Set depGroups) {
-        if(node instanceof DependentAccessNode) {
-            DependentAccessNode accessNode = (DependentAccessNode)node;
-            Command depCommand = accessNode.getCommand();
-            Collection groupSymbols = GroupCollectorVisitor.getGroups(depCommand, true);
-            Iterator groupIter = groupSymbols.iterator();
-            while(groupIter.hasNext()) {
-                GroupSymbol group = (GroupSymbol) groupIter.next();
-                depGroups.add(group.getName().toUpperCase());    
-            }
-        }
-        
-        // Recurse through children
-        RelationalNode[] children = node.getChildren();
-        for(int i=0; i<children.length; i++) {
-            if(children[i] != null) {
-                getDependentGroups(node.getChildren()[i], depGroups);                
-            }
-        }
-    }
-            
-    private void checkNotDependentGroups(ProcessorPlan plan, String[] groups) {
-        if(! (plan instanceof RelationalPlan)) {
-            return;                
-        }
-                                
-        // Collect all the group names (uppercase) for all the dependent groups in the plan
-        Set notDepGroups = new HashSet();
-        getNotDependentGroups(((RelationalPlan)plan).getRootNode(), notDepGroups);
-
-        // Check that all the expected groups exist in depGroups
-        Set expectedGroups = new HashSet();
-        for(int i=0; i<groups.length; i++) {
-            expectedGroups.add(groups[i].toUpperCase());    
-        }        
-        
-        assertEquals("Expected groups were made dependent", expectedGroups, notDepGroups);         //$NON-NLS-1$
-    }
-    
-    private void getNotDependentGroups(RelationalNode node, Set notDepGroups) {
-        if(node instanceof AccessNode && !(node instanceof DependentAccessNode)) {
-            AccessNode accessNode = (AccessNode)node;
-            Command depCommand = accessNode.getCommand();
-            Collection groupSymbols = GroupCollectorVisitor.getGroups(depCommand, true);
-            Iterator groupIter = groupSymbols.iterator();
-            while(groupIter.hasNext()) {
-                GroupSymbol group = (GroupSymbol) groupIter.next();
-                notDepGroups.add(group.getName().toUpperCase());    
-            }
-        }
-        
-        // Recurse through children
-        RelationalNode[] children = node.getChildren();
-        for(int i=0; i<children.length; i++) {
-            if(children[i] != null) {
-                getNotDependentGroups(node.getChildren()[i], notDepGroups);                
-            }
-        }
-    }
-    
-    public void testOptionMakeDep1() throws Exception {
-
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
-        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-        capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-        
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm2.g1 where pm1.g1.e1 = pm2.g1.e1 option makedep pm2.g1", FakeMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm2.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-
-        checkDependentGroups(plan, new String[] {"pm2.g1"}); //$NON-NLS-1$
-        checkNotDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });
-    }
-    
-    public void testOptionMakeDep2() throws Exception {
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
-        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-        capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-        
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1, pm2.g1.e1 from pm1.g1 MAKEDEP INNER JOIN pm2.g1 MAKENOTDEP ON pm1.g1.e1 = pm2.g1.e1", FakeMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$
-                new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm2.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-
-        checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
-        checkNotDependentGroups(plan, new String[] {"pm2.g1"}); //$NON-NLS-1$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });
-    }
-    
-    public void testDepJoinHintForceLeft() throws Exception {
-    	ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1", TestOptimizer.example1(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-        checkDependentGroups(plan, new String[] {"pm1.g1"});                             //$NON-NLS-1$
-    }
-
-    public void testDepJoinHintForceRight() throws Exception {
-        
-        ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ 
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-        checkDependentGroups(plan, new String[] {"pm1.g2"});                             //$NON-NLS-1$
-    }
-
-	public void testDepJoinMultiGroupBaseline() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1", TestOptimizer.example1(), //$NON-NLS-1$
-            new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
-                            "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
-                            "SELECT pm1.g3.e1 FROM pm1.g3" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING ); //$NON-NLS-1$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            3,      // Access
-            0,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            2,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-        checkDependentGroups(plan, new String[0]);                             
-    }
-
-    public void testDepJoinMultiGroupForceOther() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            2,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            2,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-        checkDependentGroups(plan, new String[] {"pm1.g2"});                             //$NON-NLS-1$ 
-    }
-
-    public void testDepJoinHintForceLeft_NotDep() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1 makenotdep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-        checkDependentGroups(plan, new String[] {"pm1.g1"});                             //$NON-NLS-1$
-        checkNotDependentGroups(plan, new String[] {"pm1.g2"});                             //$NON-NLS-1$
-    }
-
-    public void testDepJoinHintForceRight_NotDep() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2 makenotdep pm1.g1", TestOptimizer.example1(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-        checkDependentGroups(plan, new String[] {"pm1.g2"});                             //$NON-NLS-1$
-        checkNotDependentGroups(plan, new String[] {"pm1.g1"});                             //$NON-NLS-1$
-    }
-
-    public void testDepJoinMultiGroupForceOther_NotDep() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2 makenotdep pm1.g1, pm1.g3", TestOptimizer.example1(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            2,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            2,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-        checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ 
-        checkNotDependentGroups(plan, new String[] {"pm1.g1", "pm1.g3"}); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /**
-     * Test that access node with unsatisfied access pattern is made dependent
-     */
-    public void testMakeDependentAccessPattern1() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm1.g1.e1 = pm4.g1.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
-    }
-
-    /**
-     * Test that access node with unsatisfied access pattern is made dependent
-     * (Same query written slightly different way)
-     */
-    public void testMakeDependentAccessPattern1a() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e1 = pm1.g1.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
-    }
-    
-    /**
-     * Test that access node with unsatisfied access pattern is made dependent
-     */
-    public void testMakeDependentAccessPattern2() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e2 = 1 and pm1.g1.e1 = pm4.g1.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE (g_0.e2 = 1) AND (g_0.e1 IN (<dependent values>))", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
-    }
-
-    /**
-     * Test that second access pattern of access node is chosen to make
-     * dependent with
-     */
-    public void testMakeDependentAccessPattern3() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g2 where pm1.g1.e1 = pm4.g2.e5", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
-            new String[] { "SELECT g_0.e5 FROM pm4.g2 AS g_0 WHERE g_0.e5 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        checkDependentGroups(plan, new String[] {"pm4.g2"}); //$NON-NLS-1$
-    }
-
-    /**
-     * This case actually tests the dead-tie case - either access node could
-     * be made dependent, but merge join is used since no access pattern 
-     * needs to be fulfilled and there is no cost info available for either source
-     */
-    public void testPushSelectAndMakeDependentAccessPattern1() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
-            new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        checkDependentGroups(plan, new String[0]); 
-
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            2,      // Access
-            0,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-    }
-
-    /**
-     * This case actually tests the dead-tie case - either access node could
-     * be made dependent, but merge join is used since no access pattern 
-     * needs to be fulfilled and there is no cost info available for either source
-     * (Same query written slightly different)
-     */
-    public void testPushSelectAndMakeDependentAccessPattern1a() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e2 = pm1.g1.e2 and pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc'", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
-            new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        checkDependentGroups(plan, new String[0]); 
-    
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            2,      // Access
-            0,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-    }
-
-    /**
-     * Tests that it is enforced if an access node can't be made dependent
-     * because of it's (already-satisfied) access pattern - merge join is used
-     */
-    public void testPushSelectAndMakeDependentAccessPattern2() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
-            new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        checkDependentGroups(plan, new String[0] ); 
-
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            2,      // Access
-            0,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-    }
-    
-    /** Should use dependent join since one access node is "strong" */
-    public void testUseMergeJoin1() throws Exception {
-        // Create query
-        String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
-
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = new BasicSourceCapabilities();
-        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
-        caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
-        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(10));
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject obj = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        obj.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
-    
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
-            null, capFinder,
-            new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });         
-    }
-
-    /** Should not use a dependent join since neither access node is "strong" */
-    public void testUseMergeJoin2() throws Exception {
-        // Create query
-        String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
-
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = new BasicSourceCapabilities();
-        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject obj = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        obj.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1));
-    
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
-            null, capFinder,
-            new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2" }, TestOptimizer.ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            2,      // Access
-            0,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });         
-    }
-    
-    /** should have one dependent joins */
-    public void testMultiMergeJoin3() throws Exception {
-        // Create query
-        String sql = "SELECT pm1.g2.e1 FROM pm1.g3, pm1.g2, pm1.g1 WHERE pm1.g2.e1 = pm1.g3.e1 AND pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
-
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = new BasicSourceCapabilities();
-        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
-        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
-        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1 ));
-        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-    
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
-            null, capFinder,
-            new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            2,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            2,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });         
-    } 
-    
-    public void testMultiMergeJoin2() throws Exception {
-        String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g2.e1 = pm1.g3.e1";//$NON-NLS-1$
-
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = new BasicSourceCapabilities();
-        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
-        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-    
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
-            null, capFinder,
-            new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            2,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            2,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });         
-    } 
-
-    /**
-     * Defect 13448 
-     * should be one merge join and one dependent join
-     * Unlike the above tests, here the model pm1 supports ORDER BY.
-     */
-    public void testMultiMergeJoin5_defect13448() throws Exception {
-        // Create query
-        String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g1.e1 = pm1.g3.e1";//$NON-NLS-1$
-
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = new BasicSourceCapabilities();
-        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
-        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
-        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
-        caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
-        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-    
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
-            null, capFinder,
-            new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g3 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            2,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            2,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });         
-    }
-    
-    public void testMergeJoinVirtualGroups() throws Exception {
-        String sql = "SELECT vm1.g1.e1 FROM vm1.g1, vm1.g2a WHERE vm1.g1.e1 = vm1.g2a.e1";//$NON-NLS-1$
-
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = new BasicSourceCapabilities();
-        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
-        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
-        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
-        caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
-        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-    
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
-            null, capFinder,
-            new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });         
-    }
-    
-    public void testRLMCase2077() throws Exception {
-        
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = new BasicSourceCapabilities();
-        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
-        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-        caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
-        caps.setFunctionSupport("||", true); //$NON-NLS-1$
-        capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-        capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQT();
-        FakeMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
-        FakeMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
-         
-        ProcessorPlan plan = TestOptimizer.helpPlan(
-            "SELECT table1comp.IntKey, table1comp.key1, BQT1.SmallA.StringKey FROM (SELECT t1.*, (STRINGKEY || STRINGNUM) AS key1 FROM BQT2.SmallA AS t1) AS table1comp, BQT1.SmallA WHERE table1comp.key1 = BQT1.SmallA.StringKey",  //$NON-NLS-1$
-            metadata,
-            null, capFinder,
-            new String[] {"SELECT g_0.StringKey FROM BQT1.SmallA AS g_0 WHERE g_0.StringKey IN (<dependent values>)", "SELECT g_0.STRINGKEY, g_0.STRINGNUM, g_0.IntKey FROM BQT2.SmallA AS g_0"}, //$NON-NLS-1$ //$NON-NLS-2$
-            TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
-
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            2,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });             
-
-    }
-
-    public void testRLMCase2077_2() throws Exception {
-        
-        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        BasicSourceCapabilities caps = new BasicSourceCapabilities();
-        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
-        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-        caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
-        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
-        caps.setFunctionSupport("||", true); //$NON-NLS-1$
-        capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-        capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
-        TransformationMetadata metadata = FakeMetadataFactory.exampleBQT();
-        FakeMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
-        FakeMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
-         
-        ProcessorPlan plan = TestOptimizer.helpPlan(
-            "SELECT table1comp.IntKey, table1comp.key1, BQT1.SmallA.StringKey FROM (SELECT t1.*, (STRINGKEY || STRINGNUM) AS key1 FROM BQT2.SmallA AS t1) AS table1comp, BQT1.SmallA WHERE table1comp.key1 = BQT1.SmallA.StringKey AND table1comp.key1 = BQT1.SmallA.StringNum",  //$NON-NLS-1$
-            metadata,
-            null, capFinder,
-            new String[] {"SELECT g_0.STRINGKEY, g_0.STRINGNUM, g_0.IntKey FROM BQT2.SmallA AS g_0", "SELECT g_0.StringKey, g_0.StringNum FROM BQT1.SmallA AS g_0 WHERE (g_0.StringKey IN (<dependent values>)) AND (g_0.StringNum IN (<dependent values>))"}, //$NON-NLS-1$ //$NON-NLS-2$
-            TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
-
-        TestOptimizer.checkNodeTypes(plan, new int[] {
-            1,      // Access
-            1,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            1,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            2,      // Project
-            0,      // Select
-            0,      // Sort
-            0       // UnionAll
-        });             
-
-    }  
-
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java (from rev 2707, branches/7.2.x/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,856 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.optimizer;
+
+import static org.junit.Assert.*;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.junit.Test;
+import org.teiid.metadata.Column;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
+import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.optimizer.relational.rules.RuleChooseDependent;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.AccessNode;
+import org.teiid.query.processor.relational.DependentAccessNode;
+import org.teiid.query.processor.relational.RelationalNode;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+import org.teiid.query.unittest.FakeMetadataFacade;
+import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.FakeMetadataObject;
+
+ at SuppressWarnings("nls")
+public class TestDependentJoins {
+    
+    static void checkDependentGroups(ProcessorPlan plan, String[] groups) {
+        if(! (plan instanceof RelationalPlan)) {
+            return;                
+        }
+                                
+        // Collect all the group names (uppercase) for all the dependent groups in the plan
+        Set depGroups = new HashSet();
+        getDependentGroups(((RelationalPlan)plan).getRootNode(), depGroups);
+
+        // Check that all the expected groups exist in depGroups
+        Set expectedGroups = new HashSet();
+        for(int i=0; i<groups.length; i++) {
+            expectedGroups.add(groups[i].toUpperCase());    
+        }        
+        
+        assertEquals("Expected groups were not made dependent", expectedGroups, depGroups);         //$NON-NLS-1$
+    }
+    
+    static void getDependentGroups(RelationalNode node, Set depGroups) {
+        if(node instanceof DependentAccessNode) {
+            DependentAccessNode accessNode = (DependentAccessNode)node;
+            Command depCommand = accessNode.getCommand();
+            Collection groupSymbols = GroupCollectorVisitor.getGroups(depCommand, true);
+            Iterator groupIter = groupSymbols.iterator();
+            while(groupIter.hasNext()) {
+                GroupSymbol group = (GroupSymbol) groupIter.next();
+                depGroups.add(group.getName().toUpperCase());    
+            }
+        }
+        
+        // Recurse through children
+        RelationalNode[] children = node.getChildren();
+        for(int i=0; i<children.length; i++) {
+            if(children[i] != null) {
+                getDependentGroups(node.getChildren()[i], depGroups);                
+            }
+        }
+    }
+            
+    private void checkNotDependentGroups(ProcessorPlan plan, String[] groups) {
+        if(! (plan instanceof RelationalPlan)) {
+            return;                
+        }
+                                
+        // Collect all the group names (uppercase) for all the dependent groups in the plan
+        Set notDepGroups = new HashSet();
+        getNotDependentGroups(((RelationalPlan)plan).getRootNode(), notDepGroups);
+
+        // Check that all the expected groups exist in depGroups
+        Set expectedGroups = new HashSet();
+        for(int i=0; i<groups.length; i++) {
+            expectedGroups.add(groups[i].toUpperCase());    
+        }        
+        
+        assertEquals("Expected groups were made dependent", expectedGroups, notDepGroups);         //$NON-NLS-1$
+    }
+    
+    private void getNotDependentGroups(RelationalNode node, Set notDepGroups) {
+        if(node instanceof AccessNode && !(node instanceof DependentAccessNode)) {
+            AccessNode accessNode = (AccessNode)node;
+            Command depCommand = accessNode.getCommand();
+            Collection groupSymbols = GroupCollectorVisitor.getGroups(depCommand, true);
+            Iterator groupIter = groupSymbols.iterator();
+            while(groupIter.hasNext()) {
+                GroupSymbol group = (GroupSymbol) groupIter.next();
+                notDepGroups.add(group.getName().toUpperCase());    
+            }
+        }
+        
+        // Recurse through children
+        RelationalNode[] children = node.getChildren();
+        for(int i=0; i<children.length; i++) {
+            if(children[i] != null) {
+                getNotDependentGroups(node.getChildren()[i], notDepGroups);                
+            }
+        }
+    }
+    
+    @Test public void testOptionMakeDep1() throws Exception {
+
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+        
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm2.g1 where pm1.g1.e1 = pm2.g1.e1 option makedep pm2.g1", FakeMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm2.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+
+        checkDependentGroups(plan, new String[] {"pm2.g1"}); //$NON-NLS-1$
+        checkNotDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });
+    }
+    
+    @Test public void testOptionMakeDep2() throws Exception {
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+        
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1, pm2.g1.e1 from pm1.g1 MAKEDEP INNER JOIN pm2.g1 MAKENOTDEP ON pm1.g1.e1 = pm2.g1.e1", FakeMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$
+                new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm2.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+
+        checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
+        checkNotDependentGroups(plan, new String[] {"pm2.g1"}); //$NON-NLS-1$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });
+    }
+    
+    @Test public void testDepJoinHintForceLeft() throws Exception {
+    	ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1", TestOptimizer.example1(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+        checkDependentGroups(plan, new String[] {"pm1.g1"});                             //$NON-NLS-1$
+    }
+
+    @Test public void testDepJoinHintForceRight() throws Exception {
+        
+        ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ 
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+        checkDependentGroups(plan, new String[] {"pm1.g2"});                             //$NON-NLS-1$
+    }
+
+	@Test public void testDepJoinMultiGroupBaseline() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1", TestOptimizer.example1(), //$NON-NLS-1$
+            new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
+                            "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
+                            "SELECT pm1.g3.e1 FROM pm1.g3" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING ); //$NON-NLS-1$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            3,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            2,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+        checkDependentGroups(plan, new String[0]);                             
+    }
+
+    @Test public void testDepJoinMultiGroupForceOther() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            2,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+        checkDependentGroups(plan, new String[] {"pm1.g2"});                             //$NON-NLS-1$ 
+    }
+
+    @Test public void testDepJoinHintForceLeft_NotDep() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1 makenotdep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+        checkDependentGroups(plan, new String[] {"pm1.g1"});                             //$NON-NLS-1$
+        checkNotDependentGroups(plan, new String[] {"pm1.g2"});                             //$NON-NLS-1$
+    }
+
+    @Test public void testDepJoinHintForceRight_NotDep() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2 makenotdep pm1.g1", TestOptimizer.example1(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+        checkDependentGroups(plan, new String[] {"pm1.g2"});                             //$NON-NLS-1$
+        checkNotDependentGroups(plan, new String[] {"pm1.g1"});                             //$NON-NLS-1$
+    }
+
+    @Test public void testDepJoinMultiGroupForceOther_NotDep() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2 makenotdep pm1.g1, pm1.g3", TestOptimizer.example1(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            2,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+        checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ 
+        checkNotDependentGroups(plan, new String[] {"pm1.g1", "pm1.g3"}); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /**
+     * Test that access node with unsatisfied access pattern is made dependent
+     */
+    @Test public void testMakeDependentAccessPattern1() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm1.g1.e1 = pm4.g1.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
+    }
+
+    /**
+     * Test that access node with unsatisfied access pattern is made dependent
+     * (Same query written slightly different way)
+     */
+    @Test public void testMakeDependentAccessPattern1a() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e1 = pm1.g1.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
+    }
+    
+    /**
+     * Test that access node with unsatisfied access pattern is made dependent
+     */
+    @Test public void testMakeDependentAccessPattern2() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e2 = 1 and pm1.g1.e1 = pm4.g1.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE (g_0.e2 = 1) AND (g_0.e1 IN (<dependent values>))", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
+    }
+
+    /**
+     * Test that second access pattern of access node is chosen to make
+     * dependent with
+     */
+    @Test public void testMakeDependentAccessPattern3() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g2 where pm1.g1.e1 = pm4.g2.e5", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+            new String[] { "SELECT g_0.e5 FROM pm4.g2 AS g_0 WHERE g_0.e5 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        checkDependentGroups(plan, new String[] {"pm4.g2"}); //$NON-NLS-1$
+    }
+
+    /**
+     * This case actually tests the dead-tie case - either access node could
+     * be made dependent, but merge join is used since no access pattern 
+     * needs to be fulfilled and there is no cost info available for either source
+     */
+    @Test public void testPushSelectAndMakeDependentAccessPattern1() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+            new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        checkDependentGroups(plan, new String[0]); 
+
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+    }
+
+    /**
+     * This case actually tests the dead-tie case - either access node could
+     * be made dependent, but merge join is used since no access pattern 
+     * needs to be fulfilled and there is no cost info available for either source
+     * (Same query written slightly different)
+     */
+    @Test public void testPushSelectAndMakeDependentAccessPattern1a() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e2 = pm1.g1.e2 and pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc'", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+            new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        checkDependentGroups(plan, new String[0]); 
+    
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+    }
+
+    /**
+     * Tests that it is enforced if an access node can't be made dependent
+     * because of it's (already-satisfied) access pattern - merge join is used
+     */
+    @Test public void testPushSelectAndMakeDependentAccessPattern2() throws Exception {
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+            new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        checkDependentGroups(plan, new String[0] ); 
+
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+    }
+    
+    /** Should use dependent join since one access node is "strong" */
+    @Test public void testUseMergeJoin1() throws Exception {
+        // Create query
+        String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
+
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(10));
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject obj = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        obj.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
+    
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
+            null, capFinder,
+            new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });         
+    }
+
+    /** Should not use a dependent join since neither access node is "strong" */
+    @Test public void testUseMergeJoin2() throws Exception {
+        // Create query
+        String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
+
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject obj = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        obj.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1));
+    
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
+            null, capFinder,
+            new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2" }, TestOptimizer.ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });         
+    }
+    
+    /** should have one dependent joins */
+    @Test public void testMultiMergeJoin3() throws Exception {
+        // Create query
+        String sql = "SELECT pm1.g2.e1 FROM pm1.g3, pm1.g2, pm1.g1 WHERE pm1.g2.e1 = pm1.g3.e1 AND pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
+
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1));
+        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1 ));
+        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+    
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
+            null, capFinder,
+            new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            2,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });         
+    } 
+    
+    @Test public void testMultiMergeJoin2() throws Exception {
+        String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g2.e1 = pm1.g3.e1";//$NON-NLS-1$
+
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
+        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+    
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
+            null, capFinder,
+            new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            2,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });         
+    } 
+
+    /**
+     * Defect 13448 
+     * should be one merge join and one dependent join
+     * Unlike the above tests, here the model pm1 supports ORDER BY.
+     */
+    @Test public void testMultiMergeJoin5_defect13448() throws Exception {
+        // Create query
+        String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g1.e1 = pm1.g3.e1";//$NON-NLS-1$
+
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+        caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
+        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+    
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
+            null, capFinder,
+            new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g3 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            2,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });         
+    }
+    
+    @Test public void testMergeJoinVirtualGroups() throws Exception {
+        String sql = "SELECT vm1.g1.e1 FROM vm1.g1, vm1.g2a WHERE vm1.g1.e1 = vm1.g2a.e1";//$NON-NLS-1$
+
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+        caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
+        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+    
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
+            null, capFinder,
+            new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });         
+    }
+    
+    @Test public void testRLMCase2077() throws Exception {
+        
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+        caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+        caps.setFunctionSupport("||", true); //$NON-NLS-1$
+        capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQT();
+        FakeMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
+        FakeMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
+         
+        ProcessorPlan plan = TestOptimizer.helpPlan(
+            "SELECT table1comp.IntKey, table1comp.key1, BQT1.SmallA.StringKey FROM (SELECT t1.*, (STRINGKEY || STRINGNUM) AS key1 FROM BQT2.SmallA AS t1) AS table1comp, BQT1.SmallA WHERE table1comp.key1 = BQT1.SmallA.StringKey",  //$NON-NLS-1$
+            metadata,
+            null, capFinder,
+            new String[] {"SELECT g_0.StringKey FROM BQT1.SmallA AS g_0 WHERE g_0.StringKey IN (<dependent values>)", "SELECT g_0.STRINGKEY, g_0.STRINGNUM, g_0.IntKey FROM BQT2.SmallA AS g_0"}, //$NON-NLS-1$ //$NON-NLS-2$
+            TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
+
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            2,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });             
+
+    }
+
+    @Test public void testRLMCase2077_2() throws Exception {
+        
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+        caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+        caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+        caps.setFunctionSupport("||", true); //$NON-NLS-1$
+        capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+        TransformationMetadata metadata = FakeMetadataFactory.exampleBQT();
+        FakeMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
+        FakeMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
+         
+        ProcessorPlan plan = TestOptimizer.helpPlan(
+            "SELECT table1comp.IntKey, table1comp.key1, BQT1.SmallA.StringKey FROM (SELECT t1.*, (STRINGKEY || STRINGNUM) AS key1 FROM BQT2.SmallA AS t1) AS table1comp, BQT1.SmallA WHERE table1comp.key1 = BQT1.SmallA.StringKey AND table1comp.key1 = BQT1.SmallA.StringNum",  //$NON-NLS-1$
+            metadata,
+            null, capFinder,
+            new String[] {"SELECT g_0.STRINGKEY, g_0.STRINGNUM, g_0.IntKey FROM BQT2.SmallA AS g_0", "SELECT g_0.StringKey, g_0.StringNum FROM BQT1.SmallA AS g_0 WHERE (g_0.StringKey IN (<dependent values>)) AND (g_0.StringNum IN (<dependent values>))"}, //$NON-NLS-1$ //$NON-NLS-2$
+            TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
+
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            2,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });             
+
+    }  
+    
+    @Test public void testCostingCleanup() throws Exception {
+        
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+        caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+        capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+        TransformationMetadata metadata = FakeMetadataFactory.exampleBQT();
+        FakeMetadataFactory.setCardinality("bqt1.smalla", 3000, metadata); //$NON-NLS-1$
+        FakeMetadataFactory.setCardinality("bqt2.smalla", 10000, metadata); //$NON-NLS-1$
+        Column fmo = (Column)metadata.getElementID("bqt1.smalla.intnum");
+		fmo.setDistinctValues(1000);
+        ProcessorPlan plan = TestOptimizer.helpPlan(
+            "SELECT max(a.stringkey) from bqt1.smalla a, bqt2.smalla a2, bqt1.smalla a1 where a.intnum = a2.intnum and a1.stringnum = a2.stringnum and a.floatnum = a1.floatnum",  //$NON-NLS-1$
+            metadata,
+            null, capFinder,
+            new String[] {"SELECT g_1.stringnum AS c_0, g_0.intnum AS c_1, MAX(g_0.stringkey) AS c_2 FROM bqt1.smalla AS g_0, bqt1.smalla AS g_1 WHERE g_0.floatnum = g_1.floatnum GROUP BY g_1.stringnum, g_0.intnum ORDER BY c_0, c_1", "SELECT DISTINCT g_0.stringnum AS c_0, g_0.intnum AS c_1 FROM bqt2.smalla AS g_0 WHERE (g_0.stringnum IN (<dependent values>)) AND (g_0.intnum IN (<dependent values>)) ORDER BY c_0, c_1"},
+            TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
+
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            1,      // Access
+            1,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            1,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        });             
+
+    } 
+
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/processor/TestMaterialization.java
===================================================================
--- branches/7.2.x/engine/src/test/java/org/teiid/query/processor/TestMaterialization.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/processor/TestMaterialization.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,149 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright (C) 2009 Red Hat, Inc.
- * Licensed to Red Hat, Inc. under one or more contributor 
- * license agreements.  See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.processor;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.concurrent.Executor;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.teiid.cache.DefaultCacheFactory;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.dqp.internal.process.CachedResults;
-import org.teiid.dqp.internal.process.QueryProcessorFactoryImpl;
-import org.teiid.dqp.internal.process.SessionAwareCache;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import org.teiid.query.tempdata.TempTableDataManager;
-import org.teiid.query.tempdata.TempTableStore;
-import org.teiid.query.unittest.RealMetadataFactory;
-import org.teiid.query.util.CommandContext;
-
- at SuppressWarnings("nls")
-public class TestMaterialization {
-	
-	private TempMetadataAdapter metadata;
-	private TempTableDataManager dataManager;
-	private TempTableStore tempStore;
-	private TempTableStore globalStore;
-	private ProcessorPlan previousPlan;
-	private HardcodedDataManager hdm;
-	
-	@Before public void setUp() {
-		tempStore = new TempTableStore("1"); //$NON-NLS-1$
-		globalStore  = new TempTableStore("SYSTEM");
-		metadata = new TempMetadataAdapter(RealMetadataFactory.exampleMaterializedView(), tempStore.getMetadataStore());
-		hdm = new HardcodedDataManager();
-		hdm.addData("SELECT matsrc.x FROM matsrc", new List[] {Arrays.asList((String)null), Arrays.asList("one"), Arrays.asList("two"), Arrays.asList("three")});
-		hdm.addData("SELECT mattable.info.e1, mattable.info.e2 FROM mattable.info", new List[] {Arrays.asList("a", 1), Arrays.asList("a", 2)});
-		hdm.addData("SELECT mattable.info.e2, mattable.info.e1 FROM mattable.info", new List[] {Arrays.asList(1, "a"), Arrays.asList(2, "a")});
-		
-	    BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
-	    SessionAwareCache<CachedResults> cache = new SessionAwareCache<CachedResults>();
-	    cache.setBufferManager(bm);
-	    Executor executor = new Executor() {
-			@Override
-			public void execute(Runnable command) {
-				command.run();
-			}
-	    };
-		dataManager = new TempTableDataManager(hdm, bm, executor, cache, cache, new DefaultCacheFactory());
-	}
-	
-	private void execute(String sql, List<?>... expectedResults) throws Exception {
-		CommandContext cc = TestProcessor.createCommandContext();
-		cc.setTempTableStore(tempStore);
-		cc.setGlobalTableStore(globalStore);
-		cc.setMetadata(metadata);
-		CapabilitiesFinder finder = new DefaultCapabilitiesFinder();
-		previousPlan = TestProcessor.helpGetPlan(TestProcessor.helpParse(sql), metadata, finder, cc);
-		cc.setQueryProcessorFactory(new QueryProcessorFactoryImpl(BufferManagerFactory.getStandaloneBufferManager(), dataManager, finder, null, metadata));
-		TestProcessor.doProcess(previousPlan, dataManager, expectedResults, cc);
-	}
-
-	@Test public void testPopulate() throws Exception {
-		execute("SELECT * from vgroup3 where x = 'one'", Arrays.asList("one", "zne"));
-		assertEquals(1, hdm.getCommandHistory().size());
-		execute("SELECT * from vgroup3 where x is null", Arrays.asList(null, null));
-		assertEquals(1, hdm.getCommandHistory().size());
-	}
-	
-    @Test(expected=TeiidProcessingException.class) public void testCodeTableResponseException() throws Exception {
-    	//duplicate key
-    	execute("select lookup('mattable.info', 'e2', 'e1', 'a')");
-    }
-    
-    @Test public void testCodeTable() throws Exception {
-    	execute("select lookup('mattable.info', 'e1', 'e2', 5)", Arrays.asList((String)null));
-    	assertEquals(1, hdm.getCommandHistory().size());
-    	execute("select lookup('mattable.info', 'e1', 'e2', 1)", Arrays.asList("a"));
-    	assertEquals(1, hdm.getCommandHistory().size());
-    }
-    
-	@Test public void testTtl() throws Exception {
-		execute("SELECT * from vgroup4 where x = 'one'", Arrays.asList("one"));
-		assertEquals(1, hdm.getCommandHistory().size());
-		execute("SELECT * from vgroup4 where x is null", Arrays.asList((String)null));
-		assertEquals(1, hdm.getCommandHistory().size());
-		Thread.sleep(150);
-		execute("SELECT * from vgroup4 where x is null", Arrays.asList((String)null));
-		assertEquals(2, hdm.getCommandHistory().size());
-	}
-	
-	@Test public void testProcedureCache() throws Exception {
-		execute("call sp1('one')", Arrays.asList("one"));
-		assertEquals(1, hdm.getCommandHistory().size());
-		execute("call sp1('one')", Arrays.asList("one"));
-		assertEquals(1, hdm.getCommandHistory().size());
-		execute("call sp1('one') option nocache sp.sp1", Arrays.asList("one"));
-		assertEquals(2, hdm.getCommandHistory().size());
-		execute("call sp1(null)");
-		assertEquals(3, hdm.getCommandHistory().size());
-		execute("call sp1(null)");
-		assertEquals(3, hdm.getCommandHistory().size());
-	}
-	
-	@Test public void testCoveringSecondaryIndex() throws Exception {
-		execute("SELECT * from vgroup3 where y in ('zne', 'zwo') order by y desc", Arrays.asList("two", "zwo"), Arrays.asList("one", "zne"));
-		execute("SELECT * from vgroup3 where y is null", Arrays.asList((String)null, (String)null));
-	}
-	
-	@Test public void testNonCoveringSecondaryIndex() throws Exception {
-		execute("SELECT * from vgroup5 where y in ('zne', 'zwo') order by y desc", Arrays.asList("two", "zwo", 1), Arrays.asList("one", "zne", 1));
-		execute("SELECT * from vgroup5 where y is null", Arrays.asList((String)null, (String)null, 1));
-		execute("SELECT * from vgroup5 where y is null and z = 2");
-	}
-	
-	@Test public void testNonCoveringSecondaryIndexWithoutPrimaryKey() throws Exception {
-		execute("SELECT * from vgroup6 where y in ('zne', 'zwo') order by y desc", Arrays.asList("two", "zwo"), Arrays.asList("one", "zne"));
-		execute("SELECT * from vgroup6 where y is null", Arrays.asList((String)null, (String)null));
-	}
-    
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/processor/TestMaterialization.java (from rev 2707, branches/7.2.x/engine/src/test/java/org/teiid/query/processor/TestMaterialization.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/processor/TestMaterialization.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/processor/TestMaterialization.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,153 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright (C) 2009 Red Hat, Inc.
+ * Licensed to Red Hat, Inc. under one or more contributor 
+ * license agreements.  See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.processor;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.teiid.cache.DefaultCacheFactory;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.dqp.internal.process.CachedResults;
+import org.teiid.dqp.internal.process.QueryProcessorFactoryImpl;
+import org.teiid.dqp.internal.process.SessionAwareCache;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.tempdata.TempTableDataManager;
+import org.teiid.query.tempdata.TempTableStore;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings("nls")
+public class TestMaterialization {
+	
+	private TempMetadataAdapter metadata;
+	private TempTableDataManager dataManager;
+	private TempTableStore tempStore;
+	private TempTableStore globalStore;
+	private ProcessorPlan previousPlan;
+	private HardcodedDataManager hdm;
+	
+	@Before public void setUp() {
+		tempStore = new TempTableStore("1"); //$NON-NLS-1$
+		globalStore  = new TempTableStore("SYSTEM");
+		metadata = new TempMetadataAdapter(RealMetadataFactory.exampleMaterializedView(), tempStore.getMetadataStore());
+		hdm = new HardcodedDataManager();
+		hdm.addData("SELECT matsrc.x FROM matsrc", new List[] {Arrays.asList((String)null), Arrays.asList("one"), Arrays.asList("two"), Arrays.asList("three")});
+		hdm.addData("SELECT mattable.info.e1, mattable.info.e2 FROM mattable.info", new List[] {Arrays.asList("a", 1), Arrays.asList("a", 2)});
+		hdm.addData("SELECT mattable.info.e2, mattable.info.e1 FROM mattable.info", new List[] {Arrays.asList(1, "a"), Arrays.asList(2, "a")});
+		
+	    BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
+	    SessionAwareCache<CachedResults> cache = new SessionAwareCache<CachedResults>();
+	    cache.setBufferManager(bm);
+	    Executor executor = new Executor() {
+			@Override
+			public void execute(Runnable command) {
+				command.run();
+			}
+	    };
+		dataManager = new TempTableDataManager(hdm, bm, executor, cache, cache, new DefaultCacheFactory());
+	}
+	
+	private void execute(String sql, List<?>... expectedResults) throws Exception {
+		CommandContext cc = TestProcessor.createCommandContext();
+		cc.setTempTableStore(tempStore);
+		cc.setGlobalTableStore(globalStore);
+		cc.setMetadata(metadata);
+		CapabilitiesFinder finder = new DefaultCapabilitiesFinder();
+		previousPlan = TestProcessor.helpGetPlan(TestProcessor.helpParse(sql), metadata, finder, cc);
+		cc.setQueryProcessorFactory(new QueryProcessorFactoryImpl(BufferManagerFactory.getStandaloneBufferManager(), dataManager, finder, null, metadata));
+		TestProcessor.doProcess(previousPlan, dataManager, expectedResults, cc);
+	}
+
+	@Test public void testPopulate() throws Exception {
+		execute("SELECT * from vgroup3 where x = 'one'", Arrays.asList("one", "zne"));
+		assertEquals(1, hdm.getCommandHistory().size());
+		execute("SELECT * from vgroup3 where x is null", Arrays.asList(null, null));
+		assertEquals(1, hdm.getCommandHistory().size());
+	}
+	
+    @Test(expected=TeiidProcessingException.class) public void testCodeTableResponseException() throws Exception {
+    	//duplicate key
+    	execute("select lookup('mattable.info', 'e2', 'e1', 'a')");
+    }
+    
+    @Test public void testCodeTable() throws Exception {
+    	execute("select lookup('mattable.info', 'e1', 'e2', 5)", Arrays.asList((String)null));
+    	assertEquals(1, hdm.getCommandHistory().size());
+    	execute("select lookup('mattable.info', 'e1', 'e2', 1)", Arrays.asList("a"));
+    	assertEquals(1, hdm.getCommandHistory().size());
+    }
+    
+	@Test public void testTtl() throws Exception {
+		execute("SELECT * from vgroup4 where x = 'one'", Arrays.asList("one"));
+		assertEquals(1, hdm.getCommandHistory().size());
+		execute("SELECT * from vgroup4 where x is null", Arrays.asList((String)null));
+		assertEquals(1, hdm.getCommandHistory().size());
+		Thread.sleep(150);
+		execute("SELECT * from vgroup4 where x is null", Arrays.asList((String)null));
+		assertEquals(2, hdm.getCommandHistory().size());
+	}
+	
+	@Test public void testProcedureCache() throws Exception {
+		execute("call sp1('one')", Arrays.asList("one"));
+		assertEquals(1, hdm.getCommandHistory().size());
+		execute("call sp1('one')", Arrays.asList("one"));
+		assertEquals(1, hdm.getCommandHistory().size());
+		execute("call sp1('one') option nocache sp.sp1", Arrays.asList("one"));
+		assertEquals(2, hdm.getCommandHistory().size());
+		execute("call sp1(null)");
+		assertEquals(3, hdm.getCommandHistory().size());
+		execute("call sp1(null)");
+		assertEquals(3, hdm.getCommandHistory().size());
+	}
+	
+	@Test public void testCoveringSecondaryIndex() throws Exception {
+		execute("SELECT * from vgroup3 where y in ('zne', 'zwo') order by y desc", Arrays.asList("two", "zwo"), Arrays.asList("one", "zne"));
+		execute("SELECT * from vgroup3 where y is null", Arrays.asList((String)null, (String)null));
+	}
+	
+	@Test public void testNonCoveringSecondaryIndex() throws Exception {
+		execute("SELECT * from vgroup5 where y in ('zne', 'zwo') order by y desc", Arrays.asList("two", "zwo", 1), Arrays.asList("one", "zne", 1));
+		execute("SELECT * from vgroup5 where y is null", Arrays.asList((String)null, (String)null, 1));
+		execute("SELECT * from vgroup5 where y is null and z = 2");
+	}
+	
+	@Test public void testNonCoveringSecondaryIndexWithoutPrimaryKey() throws Exception {
+		execute("SELECT * from vgroup6 where y in ('zne', 'zwo') order by y desc", Arrays.asList("two", "zwo"), Arrays.asList("one", "zne"));
+		execute("SELECT * from vgroup6 where y is null", Arrays.asList((String)null, (String)null));
+	}
+	
+	@Test public void testPrimaryKeyOnOtherColumn() throws Exception {
+		execute("SELECT * from vgroup7 where y is null", Arrays.asList("1", null, 1));
+	}
+    
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
===================================================================
--- branches/7.2.x/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,2309 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.rewriter;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Properties;
-import java.util.TimeZone;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.TimestampWithTimezone;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.resolver.util.ResolverVisitor;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.ExpressionSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.SearchedCaseExpression;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.util.ContextProperties;
-
-
- at SuppressWarnings("nls")
-public class TestQueryRewriter {
-
-    private static final String TRUE_STR = "1 = 1"; //$NON-NLS-1$
-    private static final String FALSE_STR = "1 = 0"; //$NON-NLS-1$
-
-    // ################################## TEST HELPERS ################################
-    
-    private Criteria parseCriteria(String critStr, QueryMetadataInterface metadata) {
-        try {
-            Criteria crit = QueryParser.getQueryParser().parseCriteria(critStr);
-            
-            // resolve against metadata
-            QueryResolver.resolveCriteria(crit, metadata);
-            
-            return crit;
-        } catch(TeiidException e) {
-            throw new RuntimeException(e);
-        }   
-    }
-    
-    private Criteria helpTestRewriteCriteria(String original, String expected) {
-        try {
-            return helpTestRewriteCriteria(original, expected, false);
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        } 
-    }   
-    
-    private Criteria helpTestRewriteCriteria(String original, String expected, boolean rewrite) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
-        Criteria expectedCrit = parseCriteria(expected, metadata);
-        if (rewrite) {
-            QueryResolver.resolveCriteria(expectedCrit, metadata);
-            expectedCrit = QueryRewriter.rewriteCriteria(expectedCrit, null, null, metadata);
-        }
-        return helpTestRewriteCriteria(original, expectedCrit, metadata);
-    }
-
-    private Criteria helpTestRewriteCriteria(String original, Criteria expectedCrit, QueryMetadataInterface metadata) {
-        Criteria origCrit = parseCriteria(original, metadata);
-        
-        Criteria actual = null;
-        // rewrite
-        try { 
-            actual = QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
-            assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
-        } catch(TeiidException e) { 
-        	throw new RuntimeException(e);
-        }
-        return actual;
-    }  
-    
-    private Expression helpTestRewriteExpression(String original, String expected, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
-    	Expression actualExp = QueryParser.getQueryParser().parseExpression(original);
-    	ResolverVisitor.resolveLanguageObject(actualExp, metadata);
-    	CommandContext context = new CommandContext();
-    	context.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
-    	actualExp = QueryRewriter.rewriteExpression(actualExp, null, context, metadata);
-    	if (expected != null) {
-	    	Expression expectedExp = QueryParser.getQueryParser().parseExpression(expected);
-	    	ResolverVisitor.resolveLanguageObject(expectedExp, metadata);
-	    	assertEquals(expectedExp, actualExp);
-    	}
-    	return actualExp;
-    }
-    
-	private String getRewritenProcedure(String procedure, String userUpdateStr, String procedureType) throws TeiidComponentException, TeiidProcessingException {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
-
-        return getRewritenProcedure(userUpdateStr, metadata);
-	}
-
-	private String getRewritenProcedure(String userUpdateStr,
-			QueryMetadataInterface metadata) throws TeiidComponentException,
-			QueryMetadataException, TeiidProcessingException {
-		ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr); 
-        QueryResolver.resolveCommand(userCommand, metadata);
-        CreateUpdateProcedureCommand proc = (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, null);
-		QueryRewriter.rewrite(userCommand, metadata, null);
-		Command result = QueryRewriter.rewrite(proc, metadata, null);
-		return result.toString();
-	}
-	
-    static Command helpTestRewriteCommand(String original, String expected) { 
-        try {
-            return helpTestRewriteCommand(original, expected, FakeMetadataFactory.example1Cached());
-        } catch(TeiidException e) { 
-            throw new TeiidRuntimeException(e);
-        }
-    }
-    
-    static Command helpTestRewriteCommand(String original, String expected, QueryMetadataInterface metadata) throws TeiidException { 
-        Command command = QueryParser.getQueryParser().parseCommand(original);            
-        QueryResolver.resolveCommand(command, metadata);
-        Command rewriteCommand = QueryRewriter.rewrite(command, metadata, null);
-        assertEquals("Rewritten command was not expected", expected, rewriteCommand.toString()); //$NON-NLS-1$
-        return rewriteCommand;
-    }
-    
-    @Test public void testRewriteUnknown() {
-        helpTestRewriteCriteria("pm1.g1.e1 = '1' and '1' = convert(null, string)", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteUnknown1() {
-        helpTestRewriteCriteria("pm1.g1.e1 = '1' or '1' = convert(null, string)", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteUnknown2() {
-        helpTestRewriteCriteria("not('1' = convert(null, string))", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteUnknown3() {
-        helpTestRewriteCriteria("pm1.g1.e1 like convert(null, string))", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteUnknown4() {
-        helpTestRewriteCriteria("null in ('a', 'b', 'c')", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteUnknown5() {
-        helpTestRewriteCriteria("(null <> null) and 1 = 0", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteUnknown6() {
-        helpTestRewriteCriteria("not(pm1.g1.e1 = '1' and '1' = convert(null, string))", "pm1.g1.e1 <> '1'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-        
-    @Test public void testRewriteUnknown7() {
-        helpTestRewriteCriteria("not(pm1.g1.e1 = '1' or '1' = convert(null, string))", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteUnknown8() {
-        helpTestRewriteCriteria("pm1.g1.e1 in (2, null)", "pm1.g1.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$ 
-    }
-    
-    @Test public void testRewriteInCriteriaWithRepeats() {
-        helpTestRewriteCriteria("pm1.g1.e1 in ('1', '1', '2')", "pm1.g1.e1 IN ('1', '2')"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteInCriteriaWithSingleValue() {
-        helpTestRewriteCriteria("pm1.g1.e1 in ('1')", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteInCriteriaWithSingleValue1() {
-        helpTestRewriteCriteria("pm1.g1.e1 not in ('1')", "pm1.g1.e1 != '1'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteInCriteriaWithConvert() {
-        helpTestRewriteCriteria("convert(pm1.g1.e2, string) not in ('x')", "pm1.g1.e2 IS NOT NULL"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteInCriteriaWithNoValues() throws Exception {
-    	ElementSymbol e1 = new ElementSymbol("e1");
-    	e1.setGroupSymbol(new GroupSymbol("g1"));
-        Criteria crit = new SetCriteria(e1, Collections.EMPTY_LIST); //$NON-NLS-1$
-        
-        Criteria actual = QueryRewriter.rewriteCriteria(crit, null, null, null);
-        
-        IsNullCriteria inc = new IsNullCriteria(e1);
-        inc.setNegated(true);
-        assertEquals(inc, actual);
-    }
-        
-    @Test public void testRewriteBetweenCriteria1() {
-        helpTestRewriteCriteria("pm1.g1.e1 BETWEEN 1000 AND 2000", "(pm1.g1.e1 >= '1000') AND (pm1.g1.e1 <= '2000')"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteBetweenCriteria2() {
-        helpTestRewriteCriteria("pm1.g1.e1 NOT BETWEEN 1000 AND 2000", "(pm1.g1.e1 < '1000') OR (pm1.g1.e1 > '2000')"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCrit1() {
-        helpTestRewriteCriteria("concat('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCrit2() {
-        helpTestRewriteCriteria("'x' = pm1.g1.e1", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCrit3() {
-        helpTestRewriteCriteria("pm1.g1.e1 = convert('a', string)", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCrit4() {
-        helpTestRewriteCriteria("pm1.g1.e1 = CONVERT('a', string)", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCrit5() {
-        helpTestRewriteCriteria("pm1.g1.e1 in ('a')", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit6() {
-        helpTestRewriteCriteria("1 = convert(pm1.g1.e1,integer) + 10", "pm1.g1.e1 = '-9'"); //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-    
-    @Test public void testRewriteCrit7() {
-        helpTestRewriteCriteria("((pm1.g1.e1 = 1) and (pm1.g1.e1 = 1))", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteMatchCritEscapeChar1() {
-        helpTestRewriteCriteria("pm1.g1.e1 LIKE 'x_' ESCAPE '\\'", "pm1.g1.e1 LIKE 'x_'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteMatchCritEscapeChar2() {
-        helpTestRewriteCriteria("pm1.g1.e1 LIKE '#%x' ESCAPE '#'", "pm1.g1.e1 LIKE '#%x' ESCAPE '#'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteMatchCritEscapeChar3() {
-        helpTestRewriteCriteria("pm1.g1.e1 LIKE '#%x'", "pm1.g1.e1 LIKE '#%x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteMatchCritEscapeChar4() {
-        helpTestRewriteCriteria("pm1.g1.e1 LIKE pm1.g1.e1 ESCAPE '#'", "pm1.g1.e1 LIKE pm1.g1.e1 ESCAPE '#'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteMatchCritEscapeChar5() throws Exception {
-        MatchCriteria mcrit = new MatchCriteria(new ElementSymbol("pm1.g1.e1"), new Constant(null, DataTypeManager.DefaultDataClasses.STRING), '#'); //$NON-NLS-1$
-        Criteria expected = QueryRewriter.UNKNOWN_CRITERIA; 
-                
-        Object actual = QueryRewriter.rewriteCriteria(mcrit, null, null, null); 
-        assertEquals("Did not get expected rewritten criteria", expected, actual); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteMatchCrit1() {
-        helpTestRewriteCriteria("pm1.g1.e1 LIKE 'x' ESCAPE '\\'", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteMatchCrit2() {
-        helpTestRewriteCriteria("pm1.g1.e1 NOT LIKE 'x'", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteMatchCrit3() {
-        helpTestRewriteCriteria("pm1.g1.e1 NOT LIKE '%'", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCritTimestampCreate1() {
-        helpTestRewriteCriteria("timestampCreate(pm3.g1.e2, pm3.g1.e3) = {ts'2004-11-23 09:25:00'}", "(pm3.g1.e2 = {d'2004-11-23'}) AND (pm3.g1.e3 = {t'09:25:00'})"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritTimestampCreate2() {
-        helpTestRewriteCriteria("{ts'2004-11-23 09:25:00'} = timestampCreate(pm3.g1.e2, pm3.g1.e3)", "(pm3.g1.e2 = {d'2004-11-23'}) AND (pm3.g1.e3 = {t'09:25:00'})"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritSwap1() {
-        helpTestRewriteCriteria("'x' = pm1.g1.e1", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritSwap2() {
-        helpTestRewriteCriteria("'x' <> pm1.g1.e1", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritSwap3() {
-        helpTestRewriteCriteria("'x' < pm1.g1.e1", "pm1.g1.e1 > 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritSwap4() {
-        helpTestRewriteCriteria("'x' <= pm1.g1.e1", "pm1.g1.e1 >= 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritSwap5() {
-        helpTestRewriteCriteria("'x' > pm1.g1.e1", "pm1.g1.e1 < 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritSwap6() {
-        helpTestRewriteCriteria("'x' >= pm1.g1.e1", "pm1.g1.e1 <= 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritExpr_op1() {
-        helpTestRewriteCriteria("pm1.g1.e2 + 5 = 10", "pm1.g1.e2 = 5"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritExpr_op2() {
-        helpTestRewriteCriteria("pm1.g1.e2 - 5 = 10", "pm1.g1.e2 = 15"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritExpr_op3() {
-        helpTestRewriteCriteria("pm1.g1.e2 * 5 = 10", "pm1.g1.e2 = 2"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritExpr_op4() {
-        helpTestRewriteCriteria("pm1.g1.e2 / 5 = 10", "pm1.g1.e2 = 50"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritExpr_signFlip1() {
-        helpTestRewriteCriteria("pm1.g1.e2 * -5 > 10", "pm1.g1.e2 < -2"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritExpr_signFlip2() {
-        helpTestRewriteCriteria("pm1.g1.e2 * -5 >= 10", "pm1.g1.e2 <= -2"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCritExpr_signFlip3() {
-        helpTestRewriteCriteria("pm1.g1.e2 * -5 < 10", "pm1.g1.e2 > -2"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritExpr_signFlip4() {
-        helpTestRewriteCriteria("pm1.g1.e2 * -5 <= 10", "pm1.g1.e2 >= -2"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCritExpr_backwards1() {
-        helpTestRewriteCriteria("5 + pm1.g1.e2 <= 10", "pm1.g1.e2 <= 5"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritExpr_backwards2() {
-        helpTestRewriteCriteria("-5 * pm1.g1.e2 <= 10", "pm1.g1.e2 >= -2"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCritExpr_unhandled1() {
-        helpTestRewriteCriteria("5 / pm1.g1.e2 <= 10", "5 / pm1.g1.e2 <= 10"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCritExpr_unhandled2() {
-        helpTestRewriteCriteria("5 - pm1.g1.e2 <= 10", "5 - pm1.g1.e2 <= 10"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseDate() {
-        helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMMdd') = {d'2003-05-01'}", //$NON-NLS-1$
-                                "pm3.g1.e1 = '20030501'" );         //$NON-NLS-1$
-    }
-    
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseDate1() {
-        helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMM') = {d'2003-05-01'}", //$NON-NLS-1$
-                                "pm3.g1.e1 = '200305'" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="we're no longer considering parsedate directly")
-    @Test public void testRewriteCrit_parseDate2() {
-        helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMM') = {d'2003-05-02'}", //$NON-NLS-1$
-                                "1 = 0" );         //$NON-NLS-1$
-    }
-    
-    @Ignore(value="Should be moved to the validator")
-    @Test public void testRewriteCrit_invalidParseDate() {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        Criteria origCrit = parseCriteria("PARSEDATE(pm3.g1.e1, '''') = {d'2003-05-01'}", metadata); //$NON-NLS-1$
-        
-        try { 
-            QueryRewriter.rewriteCriteria(origCrit, null, null, null);
-            fail("Expected failure"); //$NON-NLS-1$
-        } catch(TeiidException e) { 
-            assertEquals("Error Code:ERR.015.001.0003 Message:Error simplifying criteria: PARSEDATE(pm3.g1.e1, '''') = {d'2003-05-01'}", e.getMessage());     //$NON-NLS-1$
-        }
-    }
-    
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseTime() {
-        helpTestRewriteCriteria("PARSETIME(pm3.g1.e1, 'HH mm ss') = {t'13:25:04'}", //$NON-NLS-1$
-                                "pm3.g1.e1 = '13 25 04'" );         //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteCrit_parseTimestamp() {
-        helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') = {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
-                                "1 = 0" );         //$NON-NLS-1$
-    }
-    
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseTimestamp1() {
-        helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') = {ts'2003-01-01 00:25:00.0'}", //$NON-NLS-1$
-                                "pm3.g1.e1 = '2003 01 25'" );         //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCrit_parseTimestamp2() {
-        helpTestRewriteCriteria("PARSETimestamp(CONVERT(pm3.g1.e2, string), 'yyyy-MM-dd') = {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
-                                "1 = 0" );         //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteCrit_parseTimestamp3() {
-        helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') <> {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
-                                "pm3.g1.e1 is not null" );         //$NON-NLS-1$
-    }
-    
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseTimestamp4() {
-        helpTestRewriteCriteria("PARSETimestamp(CONVERT(pm3.g1.e2, string), 'yyyy-MM-dd') = {ts'2003-05-01 00:00:00.0'}", //$NON-NLS-1$
-                                "pm3.g1.e2 = {d'2003-05-01'}" );         //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCrit_parseTimestamp_notEquality() {
-        helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') > {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
-                                "PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') > {ts'2003-05-01 13:25:04.5'}" );         //$NON-NLS-1$
-    }
-    
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseTimestamp_decompose() {
-        helpTestRewriteCriteria("PARSETIMESTAMP(CONCAT(FORMATDATE(pm3.g1.e2, 'yyyyMMdd'), FORMATTIME(pm3.g1.e3, 'HHmmss')), 'yyyyMMddHHmmss') = PARSETIMESTAMP('19690920183045', 'yyyyMMddHHmmss')", //$NON-NLS-1$
-        "(pm3.g1.e2 = {d'1969-09-20'}) AND (pm3.g1.e3 = {t'18:30:45'})" );         //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCrit_timestampCreate_decompose() {
-        helpTestRewriteCriteria("timestampCreate(pm3.g1.e2, pm3.g1.e3) = PARSETIMESTAMP('19690920183045', 'yyyyMMddHHmmss')", //$NON-NLS-1$
-        "(pm3.g1.e2 = {d'1969-09-20'}) AND (pm3.g1.e3 = {t'18:30:45'})" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseInteger() {
-        helpTestRewriteCriteria("parseInteger(pm1.g1.e1, '#,##0') = 1234", //$NON-NLS-1$
-                                "pm1.g1.e1 = '1,234'" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseLong() {
-        helpTestRewriteCriteria("parseLong(pm1.g1.e1, '#,##0') = convert(1234, long)", //$NON-NLS-1$
-                                "pm1.g1.e1 = '1,234'" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseBigInteger() {
-        helpTestRewriteCriteria("parseBigInteger(pm1.g1.e1, '#,##0') = convert(1234, biginteger)", //$NON-NLS-1$
-                                "pm1.g1.e1 = '1,234'" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseFloat() {
-        helpTestRewriteCriteria("parseFloat(pm1.g1.e1, '#,##0.###') = convert(1234.123, float)", //$NON-NLS-1$
-                                "pm1.g1.e1 = '1,234.123'" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseDouble() {
-        helpTestRewriteCriteria("parseDouble(pm1.g1.e1, '$#,##0.00') = convert(1234.5, double)", //$NON-NLS-1$
-                                "pm1.g1.e1 = '$1,234.50'" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCrit_parseBigDecimal() {
-        helpTestRewriteCriteria("parseBigDecimal(pm1.g1.e1, '#,##0.###') = convert(1234.1234, bigdecimal)", //$NON-NLS-1$
-                                "pm1.g1.e1 = '1,234.123'" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatDate() {
-        helpTestRewriteCriteria("formatDate(pm3.g1.e2, 'yyyyMMdd') = '20030501'", //$NON-NLS-1$
-                                "pm3.g1.e2 = {d'2003-05-01'}" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatTime() {
-        helpTestRewriteCriteria("formatTime(pm3.g1.e3, 'HH mm ss') = '13 25 04'", //$NON-NLS-1$
-                                "pm3.g1.e3 = {t'13:25:04'}" );         //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteCrit_formatTimestamp() {
-        helpTestRewriteCriteria("formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss') = '05 01, 1974 - 07:00:00'", //$NON-NLS-1$
-                                "formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss') = '05 01, 1974 - 07:00:00'" );         //$NON-NLS-1$
-    }
-    
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatTimestamp1() {
-        helpTestRewriteCriteria("formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss.S') = '05 01, 1974 - 07:00:00.0'", //$NON-NLS-1$
-                                "pm3.g1.e4 = {ts'1974-05-01 07:00:00.0'}" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatInteger() {
-        helpTestRewriteCriteria("formatInteger(pm1.g1.e2, '#,##0') = '1,234'", //$NON-NLS-1$
-                                "pm1.g1.e2 = 1234" );         //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCrit_formatInteger1() {
-        helpTestRewriteCriteria("formatInteger(pm1.g1.e2, '#5') = '105'", //$NON-NLS-1$
-                                "formatInteger(pm1.g1.e2, '#5') = '105'" );         //$NON-NLS-1$
-    }
-
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatLong() {
-        helpTestRewriteCriteria("formatLong(convert(pm1.g1.e2, long), '#,##0') = '1,234,567,890,123'", //$NON-NLS-1$
-                                "1 = 0" );         //$NON-NLS-1$
-    }
-    
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatLong1() {
-        helpTestRewriteCriteria("formatLong(convert(pm1.g1.e2, long), '#,##0') = '1,234,567,890'", //$NON-NLS-1$
-                                "pm1.g1.e2 = 1234567890" );         //$NON-NLS-1$
-    }
-    
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatTimestampInvert() { 
-        String original = "formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss.S') = ?"; //$NON-NLS-1$ 
-        String expected = "pm3.g1.e4 = parseTimestamp(?, 'MM dd, yyyy - HH:mm:ss.S')"; //$NON-NLS-1$ 
-         
-        helpTestRewriteCriteria(original, expected); 
-    } 
-     
-    @Test public void testRewriteCrit_plusInvert() { 
-        String original = "pm1.g1.e2 + 1.1 = ?"; //$NON-NLS-1$ 
-        String expected = "pm1.g1.e2 = ? - 1.1"; //$NON-NLS-1$ 
-         
-        helpTestRewriteCriteria(original, expected);
-    } 
-
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatBigInteger() throws Exception {
-        String original = "formatBigInteger(convert(pm1.g1.e2, biginteger), '#,##0') = '1,234,567,890'"; //$NON-NLS-1$
-        String expected = "pm1.g1.e2 = 1234567890"; //$NON-NLS-1$
-        
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
-        Criteria origCrit = parseCriteria(original, metadata);
-        Criteria expectedCrit = parseCriteria(expected, metadata);
-        
-        // rewrite
-        Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
-        assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
-    }
-
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatFloat() throws Exception {
-        String original = "formatFloat(convert(pm1.g1.e4, float), '#,##0.###') = '1,234.123'"; //$NON-NLS-1$
-        String expected = "pm1.g1.e4 = 1234.123046875"; //$NON-NLS-1$
-        
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
-        Criteria origCrit = parseCriteria(original, metadata);
-        
-        // rewrite
-        Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
-        assertEquals("Did not rewrite correctly: ", expected, actual.toString()); //$NON-NLS-1$
-    }
-
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatDouble() throws Exception {
-        String original = "formatDouble(convert(pm1.g1.e4, double), '$#,##0.00') = '$1,234.50'"; //$NON-NLS-1$
-        String expected = "pm1.g1.e4 = '1234.5'"; //$NON-NLS-1$
-        
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
-        Criteria origCrit = parseCriteria(original, metadata);
-        Criteria expectedCrit = parseCriteria(expected, metadata);
-        ((CompareCriteria)expectedCrit).setRightExpression(new Constant(new Double(1234.5)));
-        
-        // rewrite
-        Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
-        assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
-    }
-
-    @Ignore(value="Cannot deterime if the format is narrowing")
-    @Test public void testRewriteCrit_formatBigDecimal() throws Exception {
-        String original = "formatBigDecimal(convert(pm1.g1.e4, bigdecimal), '#,##0.###') = '1,234.5'"; //$NON-NLS-1$
-        String expected = "pm1.g1.e4 = 1234.5"; //$NON-NLS-1$
-        
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
-        Criteria origCrit = parseCriteria(original, metadata);
-        Criteria expectedCrit = parseCriteria(expected, metadata);
-        
-        // rewrite
-        Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
-        assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCritTimestampDiffDate1() {
-        helpTestRewriteCriteria("timestampdiff(SQL_TSI_DAY, {d'2003-05-15'}, {d'2003-05-17'} ) = 2", TRUE_STR); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCritTimestampDiffDate2() {
-        helpTestRewriteCriteria("timestampdiff(SQL_TSI_DAY, {d'2003-06-02'}, {d'2003-05-17'} ) = -16", TRUE_STR); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCritTimestampDiffDate3() {
-        helpTestRewriteCriteria("timestampdiff(SQL_TSI_QUARTER, {d'2002-01-25'}, {d'2003-06-01'} ) = 5", TRUE_STR); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCritTimestampDiffTime1() {
-        helpTestRewriteCriteria("timestampdiff(SQL_TSI_HOUR, {t'03:04:45'}, {t'05:05:36'} ) = 2", TRUE_STR); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCritTimestampDiffTime1_ignorecase() {
-        helpTestRewriteCriteria("timestampdiff(SQL_tsi_HOUR, {t'03:04:45'}, {t'05:05:36'} ) = 2", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteOr1() {
-        helpTestRewriteCriteria("(5 = 5) OR (0 = 1)", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteOr2() {
-        helpTestRewriteCriteria("(0 = 1) OR (5 = 5)", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteOr3() {
-        helpTestRewriteCriteria("(1 = 1) OR (5 = 5)", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteOr4() {
-        helpTestRewriteCriteria("(0 = 1) OR (4 = 5)", FALSE_STR); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteOr5() {
-        helpTestRewriteCriteria("(0 = 1) OR (4 = 5) OR (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')");         //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteOr6() {
-        helpTestRewriteCriteria("(0 = 1) OR (4 = 5) OR (pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')", "(pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')");     //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteOr7() {
-        helpTestRewriteCriteria("(pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')", "(pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')");     //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteAnd1() {
-        helpTestRewriteCriteria("(5 = 5) AND (0 = 1)", FALSE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteAnd2() {
-        helpTestRewriteCriteria("(0 = 1) AND (5 = 5)", FALSE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteAnd3() {
-        helpTestRewriteCriteria("(1 = 1) AND (5 = 5)", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteAnd4() {
-        helpTestRewriteCriteria("(0 = 1) AND (4 = 5)", FALSE_STR); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteAnd5() { 
-        helpTestRewriteCriteria("(1 = 1) AND (5 = 5) AND (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')");             //$NON-NLS-1$ //$NON-NLS-2$
-    }
- 
-    @Test public void testRewriteAnd6() { 
-        helpTestRewriteCriteria("(1 = 1) AND (5 = 5) AND (pm1.g1.e1 = 'x') and (pm1.g1.e1 = 'y')", "(pm1.g1.e1 = 'x') AND (pm1.g1.e1 = 'y')");             //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteAnd7() {
-        helpTestRewriteCriteria("(pm1.g1.e1 = 'x') AND (pm1.g1.e1 = 'y')", "(pm1.g1.e1 = 'x') AND (pm1.g1.e1 = 'y')");     //$NON-NLS-1$ //$NON-NLS-2$
-    }
-        
-    @Test public void testRewriteMixed1() {
-        helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed2() {
-        helpTestRewriteCriteria("((1=2) AND (1=1)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed3() {
-        helpTestRewriteCriteria("((1=1) AND (1=2)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed4() {
-        helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=2) AND (1=1))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed5() {
-        helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=1) AND (1=2))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed6() {
-        helpTestRewriteCriteria("((1=2) AND (1=1)) OR ((1=2) AND (1=1))", FALSE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed7() {
-        helpTestRewriteCriteria("((1=1) AND (1=2)) OR ((1=1) AND (1=2))", FALSE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed8() {
-        helpTestRewriteCriteria("((1=2) AND (1=2)) OR ((1=2) AND (1=2))", FALSE_STR); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteMixed9() {
-        helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed10() {
-        helpTestRewriteCriteria("((1=2) OR (1=1)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed11() {
-        helpTestRewriteCriteria("((1=1) OR (1=2)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed12() {
-        helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=2) OR (1=1))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed13() {
-        helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=1) OR (1=2))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed14() {
-        helpTestRewriteCriteria("((1=2) OR (1=1)) AND ((1=2) OR (1=1))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed15() {
-        helpTestRewriteCriteria("((1=1) OR (1=2)) AND ((1=1) OR (1=2))", TRUE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteMixed16() {
-        helpTestRewriteCriteria("((1=2) OR (1=2)) AND ((1=2) OR (1=2))", FALSE_STR); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteNot1() {
-        helpTestRewriteCriteria("NOT (1=1)", FALSE_STR);     //$NON-NLS-1$
-    }   
-
-    @Test public void testRewriteNot2() {
-        helpTestRewriteCriteria("NOT (1=2)", TRUE_STR);     //$NON-NLS-1$
-    }   
-    
-    @Test public void testRewriteNot3() {
-        helpTestRewriteCriteria("NOT (pm1.g1.e1='x')", "pm1.g1.e1 <> 'x'");     //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteDefect1() {
-        helpTestRewriteCriteria("(('DE' = 'LN') AND (null > '2002-01-01')) OR (('DE' = 'DE') AND (pm1.g1.e1 > '9000000'))", "(pm1.g1.e1 > '9000000')");         //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteQueryCriteriaAlwaysTrue() {
-        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE 0 = 0", //$NON-NLS-1$
-                                "SELECT e1 FROM pm1.g1"); //$NON-NLS-1$
-    }
-    
-    @Test public void testSubquery1() {
-        helpTestRewriteCommand("SELECT e1 FROM (SELECT e1 FROM pm1.g1 WHERE (1 - 1) = (0 + 0)) AS x", //$NON-NLS-1$
-                                "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x"); //$NON-NLS-1$
-    }
-
-    @Test public void testExistsSubquery() {
-        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
-                                "SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
-    }
-
-    @Test public void testCompareSubqueryANY() {
-        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' = ANY (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
-                                "SELECT e1 FROM pm1.g1 WHERE '3' = SOME (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
-    }
-
-    @Test public void testCompareSubquery() {
-        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' = SOME (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
-                                "SELECT e1 FROM pm1.g1 WHERE '3' = SOME (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
-    }
-    
-    @Test public void testCompareSubqueryUnknown() {
-        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE null = SOME (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
-                                "SELECT e1 FROM pm1.g1 WHERE null <> null"); //$NON-NLS-1$
-    }
-
-    @Test public void testINClauseSubquery() {
-        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
-                                "SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteXMLCriteria1() {
-        helpTestRewriteCriteria("context(pm1.g1.e1, pm1.g1.e1) = convert(5, string)", "context(pm1.g1.e1, pm1.g1.e1) = '5'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteXMLCriteria2() {
-        helpTestRewriteCriteria("context(pm1.g1.e1, convert(5, string)) = 2+3", "context(pm1.g1.e1, '5') = '5'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    // HAS Criteria
-    @Test public void testRewriteProcedure1() throws Exception {
-    	
-		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
-		procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		
-		String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-		
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-		
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
-				
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    // HAS Criteria
-    @Test public void testRewriteProcedure2() throws Exception {
-    	
-		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
-		procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n";		 //$NON-NLS-1$
-		procedure = procedure + "ELSE \n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n";		 //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		
-		String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
-				
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    // HAS Criteria
-    @Test public void testRewriteProcedure3() throws Exception {
-    	
-		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
-		procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n";		 //$NON-NLS-1$
-		procedure = procedure + "ELSE \n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n";		 //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		
-		String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
-				
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteProcedure4() throws Exception {
-    	
-		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
-		procedure = procedure + "IF (INPUT.e2 = 1)\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		
-		String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-		
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-		
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
-				
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }    
-    
-    // CHANGING
-    @Test public void testRewriteProcedure5() throws Exception {
-    	
-		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
-		procedure = procedure + "IF (CHANGING.e1 = 'false')\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		
-		String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
-		
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-		
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    // CHANGING
-    @Test public void testRewriteProcedure6() throws Exception {
-    	
-		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
-		procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		
-		String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
-		
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-		
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }     
-    
-    // TRANSLATE CRITERIA
-    @Test public void testRewriteProcedure7() throws Exception {
-    	
-		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
-		procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		
-		String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
-		
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT e2 FROM pm1.g1 WHERE pm1.g1.e2 = 10;\n";				 //$NON-NLS-1$
-		rewritProc = rewritProc + "END";		 //$NON-NLS-1$
-		
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    // TRANSLATE CRITERIA
-    @Test public void testRewriteProcedure8() throws Exception {
-    	
-		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
-		procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g1.e2) with (vm1.g1.e2 = convert(sqrt(pm1.g1.e2), integer));\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		
-		String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
-		
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT e2 FROM pm1.g1 WHERE convert(sqrt(pm1.g1.e2), integer) = 10;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-		
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    // rewrite input/ changing variables
-    @Test public void testRewriteProcedure9() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "Declare String var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "if(var1 = 'x' or var1 = 'y')\n"; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n";         //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2, Input.e2, CHANGING.e2, CHANGING.e1 from pm1.g1 order by CHANGING.e1 + 1;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        String userQuery = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
-        
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE String var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "IF((var1 = 'x') OR (var1 = 'y'))\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2, null, FALSE, TRUE FROM pm1.g1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-    @Test public void testRewriteProcedure10() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2) WITH (e2 = pm1.g1.e2 + 20);\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 = e2 + 50"; //$NON-NLS-1$
-        
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e2 + 20) = ((pm1.g1.e2 + 20) + 50);\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-	// virtual group elements used in procedure in if statement(HAS CRITERIA)
-    @Test public void testRewriteProcedure11() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
-		procedure = procedure + "var1 = INPUT.e1;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g1 SET e1=40";     //$NON-NLS-1$
-        
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE string var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "var1 = '40';\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-	// with complex query transform
-    @Test public void testRewriteProcedure12() throws Exception {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (x = CONCAT(e1 , 'z'));\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where x =CONCAT(x , 'y')"; //$NON-NLS-1$
-        
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE CONCAT(e1, 'z') = CONCAT(CONCAT(e1, 'z'), 'y');\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-	// with complex query transform
-    @Test public void testRewriteProcedure13() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (x = CONCAT(e1 , 'z'), y = convert(CONCAT(e1 , 'k'), integer));\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where x =CONCAT(x , 'y') and y= 1"; //$NON-NLS-1$
-        
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE (CONCAT(e1, 'z') = CONCAT(CONCAT(e1, 'z'), 'y')) AND (convert(CONCAT(e1, 'k'), integer) = 1);\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-    @Test public void testRewriteProcedure14() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e4 = sqrt(e4));\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE sqrt(e4) = 1.0;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-	
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-    @Test public void testRewriteProcedure15() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e4 = e4/50);\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE e2 = 0;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-	
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-    @Test public void testRewriteProcedure16() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE CRITERIA;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE e4 = 0.02;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-	
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-    @Test public void testRewriteProcedure17() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE LIKE CRITERIA WITH (e4 = e4/50);\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-	
-	// Bug 8212 elements in INPUT and CHANGING special groups are cese sensitive
-    @Test public void testRewriteProcedure18() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "Select Input.E1, Input.e2, CHANGING.e2, CHANGING.E1 from pm1.g1;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "INSERT into vm1.g1 (e1, E2) values('x', 1)"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT 'x', 1, TRUE, TRUE FROM pm1.g1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-	
-	// elements being set in updates are dropped if INPUT var is not available, unless a default is available
-    // Note that this test is a little odd in that it is an update inside of an insert
-    @Test public void testRewriteProcedure19() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "update pm1.g1 set e1=Input.E1, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "INSERT into vm1.g1 (E2) values(1)"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'xyz', e2 = 1, e3 = TRUE;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-	
-	// elements being set in updates are dropped if INPUT var is not available, unless a default is supplied
-    
-    //this test fails because the default for E1 'xyz' cannot be converted into a integer
-    @Test(expected=ExpressionEvaluationException.class) public void testRewriteProcedure21() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "INSERT into vm1.g1 (E3) values({b'true'})"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "UPDATE pm1.g1 SET e3 = TRUE;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		this.getRewritenProcedure(procedure, userQuery, FakeMetadataObject.Props.INSERT_PROCEDURE);
-	}
-    
-    @Test public void testRewriteProcedure21a() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "INSERT into vm1.g1 (E1) values(1)"; //$NON-NLS-1$
-
-        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = null, e2 = null, e3 = TRUE;\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                                                        FakeMetadataObject.Props.INSERT_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-
-	// none of input variables on update statement changing
-    @Test public void testRewriteProcedure22() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "update vm1.g1 set E3 = {b'true'}"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-	
-	// none of input variables on update statement changing
-    @Test public void testRewriteProcedure23() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "update pm1.g1 set e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "update vm1.g1 set E1 = 'x'"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-    
-    //with an insert, defaults are used
-    @Test public void testRewriteProcedure23a() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "update pm1.g1 set e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "INSERT into vm1.g1 (E1) values('x')"; //$NON-NLS-1$
-
-        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "UPDATE pm1.g1 SET e2 = null, e3 = TRUE;\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.INSERT_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-	// elements being set in updates are dropped if INPUT var is not available
-    @Test public void testRewriteProcedure24() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "UPDATE pm1.g1 SET e2=Input.e2 WHERE TRANSLATE LIKE CRITERIA ON (e1) WITH (e1=concat(pm1.g1.e1, '%'));\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g1 set E2=1 where e2 = 1 and e1 LIKE 'mnopxyz_'"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "UPDATE pm1.g1 SET e2 = 1 WHERE concat(pm1.g1.e1, '%') LIKE 'mnopxyz_';\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-
-	// INPUT vars in insert statements replaced by default variable when user's inser ignores values
-    @Test public void testRewriteProcedure25() throws Exception {
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "INSERT into pm1.g1 (e1,e2,e3,e4) values (Input.e1, Input.e2, Input.e3, Input.e4);"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "INSERT into vm1.g1 (E2) values (1)"; //$NON-NLS-1$
-
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES ('xyz', 1, TRUE, 123.456);\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-	
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-	@Test public void testRewriteProcedure26() throws Exception {
-		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2);\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n";         //$NON-NLS-1$
-
-		String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 = e2 + 50"; //$NON-NLS-1$
-        
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e2 = (pm1.g1.e2 + 50);\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-		assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-	
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-	@Test public void testRewriteProcedure27() throws Exception {
-		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2);\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n";         //$NON-NLS-1$
-
-		String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 LIKE 'xyz'"; //$NON-NLS-1$
-        
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1, pm1.g2 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-		assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-	}
-
-    /**
-     * Per defect 9380 - 
-     * A criteria of the form  
-     * (? + 1) < (null)  
-     * caused a problem in the QueryRewriter.simplifyMathematicalCriteria method.
-     * At the beginning of the method, the null constant is rewritten so that it
-     * loses it's implicit type conversion to integer, then later on a function
-     * descriptor couldn't be found for the "minus" operation for the two types 
-     * integer and MetaMatrix's null type.
-     */
-    @Test public void testRewriteProcedure_9380() throws Exception {
-        
-        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
-        procedure = procedure + "if((var1 + 1) < length(input.e1))\n"; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n";         //$NON-NLS-1$
-        procedure = procedure + "var2 = INPUT.e2;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g1 SET e2=30";     //$NON-NLS-1$
-        
-        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "BEGIN\n";         //$NON-NLS-1$
-        rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "DECLARE integer var2;\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
-        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    //base test.  no change is expected
-    @Test public void testRewriteLookupFunction1() {
-        String criteria = "lookup('pm1.g1','e1', 'e2', 1) = 'ab'"; //$NON-NLS-1$
-        CompareCriteria expected = (CompareCriteria)parseCriteria(criteria, FakeMetadataFactory.example1Cached()); 
-        helpTestRewriteCriteria(criteria, expected, FakeMetadataFactory.example1Cached());
-    }
-    
-    @Test public void testRewriteLookupFunction1b() {
-        helpTestRewriteCriteria("lookup('pm1.g1','e1', 'e2', pm1.g1.e2) = 'ab'", "lookup('pm1.g1','e1', 'e2', pm1.g1.e2) = 'ab'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** defect 11630 1 should still get rewritten as '1'*/
-    @Test public void testRewriteLookupFunctionCompoundCriteria() {
-        String criteria = "LOOKUP('pm1.g1','e1', 'e2', 1) IS NULL AND pm1.g1.e1='1'"; //$NON-NLS-1$
-        CompoundCriteria expected = (CompoundCriteria)parseCriteria(criteria, FakeMetadataFactory.example1Cached()); 
-        helpTestRewriteCriteria("LOOKUP('pm1.g1','e1', 'e2', 1) IS NULL AND pm1.g1.e1=1", expected, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
-    }
-
-    @Test public void testSelectWithNoFrom() {
-        helpTestRewriteCommand("SELECT 5", "SELECT 5"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    //defect 9822
-    @Test public void testStoredProcedure_9822() throws Exception {
-
-        QueryParser parser = new QueryParser();
-        Command command = parser.parseCommand("exec pm1.sp4(5)");             //$NON-NLS-1$
-        
-        // resolve
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        QueryResolver.resolveCommand(command, metadata);
-        
-        // rewrite
-        Command rewriteCommand = QueryRewriter.rewrite(command, metadata, null);
-        
-        List<SPParameter> parameters = ((StoredProcedure)rewriteCommand).getParameters();
-
-        for (SPParameter param : parameters) {
-            if(param.getParameterType() == ParameterInfo.IN || param.getParameterType() == ParameterInfo.INOUT){
-                assertTrue(param.getExpression() instanceof Constant);
-            }
-        }  
-    }
-    
-    @Test public void testRewriteFunctionThrowsEvaluationError() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
-        Criteria origCrit = parseCriteria("5 / 0 = 5", metadata); //$NON-NLS-1$
-        
-        // rewrite
-        try { 
-            QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
-            fail("Expected QueryValidatorException due to divide by 0"); //$NON-NLS-1$
-        } catch(TeiidException e) {
-        	// looks like message is being wrapped with another exception with same message
-            assertEquals("Error Code:ERR.015.001.0003 Message:Unable to evaluate (5 / 0): Error Code:ERR.015.001.0003 Message:Error while evaluating function /", e.getMessage());  //$NON-NLS-1$
-        }       
-    }
-    
-    @Test public void testRewriteConvertThrowsEvaluationError() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
-        Criteria origCrit = parseCriteria("convert('x', integer) = 0", metadata); //$NON-NLS-1$
-        
-        // rewrite
-        try { 
-            QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
-            fail("Expected QueryValidatorException due to invalid string"); //$NON-NLS-1$
-        } catch(TeiidException e) {
-            assertEquals("Error Code:ERR.015.001.0003 Message:Unable to evaluate convert('x', integer): Error Code:ERR.015.001.0003 Message:Error while evaluating function convert", e.getMessage()); //$NON-NLS-1$
-        }       
-    }
-    
-    @Test public void testDefect13458() throws Exception {
-    	
-		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
-		procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		procedure = procedure + "END\n"; //$NON-NLS-1$
-		
-		String userQuery = "delete from vm1.g1 where e1='1'"; //$NON-NLS-1$
-		
-		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1;\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "END"; //$NON-NLS-1$
-		
-		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.DELETE_PROCEDURE);				
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteCase1954() {
-        helpTestRewriteCriteria("convert(pm1.g1.e2, string) = '3'", "pm1.g1.e2 = 3"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCase1954a() {
-        helpTestRewriteCriteria("cast(pm1.g1.e2 as string) = '3'", "pm1.g1.e2 = 3"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCase1954b() throws Exception{
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
-
-        CompareCriteria expected = new CompareCriteria();
-        ElementSymbol leftElement = new ElementSymbol("pm1.g1.e4"); //$NON-NLS-1$
-        Constant constant = new Constant(new Double(3.0), DataTypeManager.DefaultDataClasses.DOUBLE);
-        expected.setLeftExpression(leftElement);
-        expected.setRightExpression(constant);
-        // resolve against metadata
-        QueryResolver.resolveCriteria(expected, metadata);
-        
-        helpTestRewriteCriteria("convert(pm1.g1.e4, string) = '3.0'", expected, metadata); //$NON-NLS-1$ 
-    }    
-
-    @Test public void testRewriteCase1954c() {
-        helpTestRewriteCriteria("convert(pm1.g1.e1, string) = 'x'", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteCase1954d() {
-        helpTestRewriteCriteria("convert(pm1.g1.e1, timestamp) = {ts '2005-01-03 00:00:00.0'}", "pm1.g1.e1 = '2005-01-03 00:00:00.0'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCase1954e() {
-        helpTestRewriteCriteria("convert(pm1.g1.e4, integer) = 2", "convert(pm1.g1.e4, integer) = 2"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** Check that this fails, x is not convertable to an int */
-    @Test public void testRewriteCase1954f() {
-        helpTestRewriteCriteria("convert(pm1.g1.e2, string) = 'x'", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** Check that this returns true, x is not convertable to an int */
-    @Test public void testRewriteCase1954f1() {
-        helpTestRewriteCriteria("convert(pm1.g1.e2, string) != 'x'", "pm1.g1.e2 is not null"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCase1954Set() {
-        helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', '3')", "pm1.g1.e2 IN (2,3)"); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testRewriteCase1954SetA() {
-        helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', 'x')", "pm1.g1.e2 = 2"); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    @Test public void testRewriteCase1954SetB() {
-        helpTestRewriteCriteria("cast(pm1.g1.e2 as string) in ('2', '3')", "pm1.g1.e2 IN (2,3)"); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    @Test public void testRewriteCase1954SetC() {
-        helpTestRewriteCriteria("concat(pm1.g1.e2, 'string') in ('2', '3')", "concat(pm1.g1.e2, 'string') in ('2', '3')"); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testRewriteCase1954SetD() {
-        helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', pm1.g1.e1)", "convert(pm1.g1.e2, string) in ('2', pm1.g1.e1)"); //$NON-NLS-1$ //$NON-NLS-2$
-    }      
-    
-    // First WHEN always true, so rewrite as THEN expression
-    @Test public void testRewriteCaseExpr1() {
-        helpTestRewriteCriteria("case when 0=0 then 1 else 2 end = 1", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    // First WHEN always false, so rewrite as ELSE expression
-    @Test public void testRewriteCaseExpr2() {
-        helpTestRewriteCriteria("case when 0=1 then 1 else 2 end = 1", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    // First WHEN can't be rewritten, so no changes
-    @Test public void testRewriteCaseExpr3() {
-        helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then 1 else 2 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 1 ELSE 2 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCaseExpr4() {
-        helpTestRewriteCriteria("lookup('pm1.g1', 'e2', 'e1', case when 1=1 then pm1.g1.e1 end) = 0", "lookup('pm1.g1', 'e2', 'e1', pm1.g1.e1) = 0"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    // First WHEN always false, so remove it
-    @Test public void testRewriteCaseExpr5() {
-        helpTestRewriteCriteria("case when 0=1 then 1 when 0 = pm1.g1.e2 then 2 else 3 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 2 ELSE 3 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCaseExprForCase5413aFrom502() {
-        helpTestRewriteCriteria("pm1.g2.e1 = case when 0 = pm1.g1.e2 then 2 else 2 end", "pm1.g2.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCaseExprForCase5413bFrom502() {
-        helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then null else null end IS NULL", TRUE_STR); //$NON-NLS-1$ 
-    }
-    
-    
-    @Test public void testRewriteCaseExprForCase5413a() {
-        helpTestRewriteCriteria("pm1.g2.e1 = case when 0 = pm1.g1.e2 then 2 else 2 end", "pm1.g2.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteCaseExprForCase5413b() {
-        helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then null else null end IS NULL", TRUE_STR); //$NON-NLS-1$ 
-    }
-
-    // First WHEN always true, so rewrite as THEN expression
-    @Test public void testRewriteSearchedCaseExpr1() {
-        helpTestRewriteCriteria("case 0 when 0 then 1 else 2 end = 1", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    // First WHEN always false, so rewrite as ELSE expression
-    @Test public void testRewriteSearchedCaseExpr2() {
-        helpTestRewriteCriteria("case 0 when 1 then 1 else 2 end = 1", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteSearchedCaseExpr3() {
-        helpTestRewriteCriteria("case 0 when pm1.g1.e2 then 1 else 2 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 1 ELSE 2 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteSearchedCaseExpr4() {
-        String criteria = "lookup('pm1.g1', 'e2', 'e1', '2') = 0"; //$NON-NLS-1$
-        CompareCriteria expected = (CompareCriteria)parseCriteria(criteria, FakeMetadataFactory.example1Cached()); 
-        helpTestRewriteCriteria("lookup('pm1.g1', 'e2', 'e1', case 0 when 1 then pm1.g1.e1 else 2 end) = 0", expected, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-    }
-
-    // First WHEN always false, so remove it
-    @Test public void testRewriteSearchedCaseExpr5() {
-        helpTestRewriteCriteria("case 0 when 1 then 1 when pm1.g1.e2 then 2 else 3 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 2 ELSE 3 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testDefect16879_1(){
-    	helpTestRewriteCommand("SELECT decodestring(e1, 'a, b') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testDefect16879_2(){
-    	helpTestRewriteCommand("SELECT decodestring(e1, 'a, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testDefect16879_3(){
-    	helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testDefect16879_4(){
-    	helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testDefect16879_5(){
-        helpTestRewriteCommand("SELECT decodeinteger(e1, 'null, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 IS NULL THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testDefect16879_6(){
-        helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, null, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 IS NULL THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testDefect16879_7(){
-        helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, null, d, e') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 IS NULL THEN 'd' ELSE 'e' END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testCaseExpressionThatResolvesToNull() {
-        String sqlBefore = "SELECT CASE 'x' WHEN 'Old Inventory System' THEN NULL WHEN 'New Inventory System' THEN NULL END"; //$NON-NLS-1$
-        String sqlAfter = "SELECT null"; //$NON-NLS-1$
-
-        Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
-        
-        ExpressionSymbol es = (ExpressionSymbol)cmd.getProjectedSymbols().get(0);
-        assertEquals( DataTypeManager.DefaultDataClasses.STRING, es.getType() );
-    }
-
-
-    //note that the env is now treated as deterministic, however it is really only deterministic within a session
-    @Test public void testRewriteExecEnv() throws Exception {
-        Command command = QueryParser.getQueryParser().parseCommand("exec pm1.sq2(env('sessionid'))");             //$NON-NLS-1$
-        
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
-        
-        CommandContext context = new CommandContext();
-        Properties props = new Properties();
-        props.setProperty(ContextProperties.SESSION_ID, "1"); //$NON-NLS-1$
-        context.setEnvironmentProperties(props);
-        Command rewriteCommand = QueryRewriter.rewrite(command, FakeMetadataFactory.example1Cached(), context);
-        
-        assertEquals("EXEC pm1.sq2('1')", rewriteCommand.toString()); //$NON-NLS-1$
-    }
-
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteNestedFunctions() {
-        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 where convert(parsedate(e1, 'yyyy-MM-dd'), string) = '2006-07-01'", "SELECT e1 FROM pm1.g1 WHERE e1 = '2006-07-01'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Ignore(value="It's not generally possible to invert a narrowing conversion")
-    @Test public void testRewriteWithReference() {
-        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 where parsetimestamp(e1, 'yyyy-MM-dd') != ?", "SELECT e1 FROM pm1.g1 WHERE e1 <> formattimestamp(?, 'yyyy-MM-dd')"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewiteJoinCriteria() {
-        helpTestRewriteCommand("SELECT pm1.g1.e1 FROM pm1.g1 inner join pm1.g2 on (pm1.g1.e1 = null)", "SELECT pm1.g1.e1 FROM pm1.g1 INNER JOIN pm1.g2 ON 1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewiteCompoundCriteria() {
-        helpTestRewriteCriteria("(pm1.g1.e1 = 1 and pm1.g1.e2 = 2) and (pm1.g1.e3 = 1 and pm1.g1.e4 = 2)", "(pm1.g1.e1 = '1') AND (pm1.g1.e2 = 2) AND (pm1.g1.e3 = TRUE) AND (pm1.g1.e4 = 2.0)"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteWhile() throws Exception {
-        
-        String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n";       //$NON-NLS-1$
-        procedure = procedure + "while (1 = 1)\n"; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "Select vm1.g1.e1 from vm1.g1;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-        
-        String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
-        try {       
-            getRewritenProcedure(procedure, userQuery, FakeMetadataObject.Props.INSERT_PROCEDURE);
-            fail("exception expected"); //$NON-NLS-1$
-        } catch (QueryValidatorException e) {
-            assertEquals("Infinite loop detected, procedure will not be executed.", e.getMessage()); //$NON-NLS-1$
-        }
-    }
-    
-    @Test public void testRewriteWhile1() throws Exception {
-        
-        String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n";       //$NON-NLS-1$
-        procedure = procedure + "while (1 = 0)\n"; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "Select vm1.g1.e1 from vm1.g1;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-        
-        String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-        
-        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "BEGIN\n";         //$NON-NLS-1$
-        rewritProc = rewritProc + "END"; //$NON-NLS-1$
-        
-        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.INSERT_PROCEDURE);
-                
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    /**
-     * Tests that VariableSubstitutionVisitor does not cause an NPE on count(*)
-     */
-    @Test public void testRewriteProcedureWithCount() throws Exception {
-        
-        String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n";         //$NON-NLS-1$
-        procedure = procedure + "Select count(*) from pm1.g1;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-        
-        String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-        
-        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "BEGIN\n";         //$NON-NLS-1$
-        rewritProc = rewritProc + "SELECT COUNT(*) FROM pm1.g1;\n";         //$NON-NLS-1$
-        rewritProc = rewritProc + "END"; //$NON-NLS-1$
-        
-        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.INSERT_PROCEDURE);
-                
-        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
-    }
-    
-    /**
-     * Test to ensure the update changing list retains e1 = ?
-     */
-    @Test public void testVariableSubstitutionVisitor() throws Exception {
-        String procedure1 = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure1 += "BEGIN\n"; //$NON-NLS-1$
-        procedure1 += "DECLARE string var1 = INPUT.e1;\n"; //$NON-NLS-1$
-        procedure1 += "ROWS_UPDATED = UPDATE vm1.g2 SET e1=var1;\n"; //$NON-NLS-1$
-        procedure1 += "END"; //$NON-NLS-1$
-        
-        String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
-        procedure2 += "BEGIN\n"; //$NON-NLS-1$
-        procedure2 += "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure2 += "IF (INPUT.e1 = 1)\n"; //$NON-NLS-1$
-        procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
-        procedure2 += "ELSE\n"; //$NON-NLS-1$
-        procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
-        procedure2 += "END"; //$NON-NLS-1$
-
-        String userUpdateStr = "UPDATE vm1.g1 SET e1 = 'x' WHERE e2 = 5"; //$NON-NLS-1$
-        
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure1, procedure2);
-        
-        String rewriten = getRewritenProcedure(userUpdateStr, metadata);
-        
-        String expected = "CREATE PROCEDURE\nBEGIN\nDECLARE string var1 = 'x';\nUPDATE vm1.g2 SET e1 = var1;\nROWS_UPDATED = VARIABLES.ROWCOUNT;\nEND"; //$NON-NLS-1$
-        
-        assertEquals(expected, rewriten);
-    }
-    
-    @Test public void testRemoveEmptyLoop() {
-        String procedure1 = "CREATE virtual PROCEDURE  "; //$NON-NLS-1$
-        procedure1 += "BEGIN\n"; //$NON-NLS-1$
-        procedure1 += "loop on (select e1 from pm1.g1) as myCursor\n"; //$NON-NLS-1$
-        procedure1 += "begin\n"; //$NON-NLS-1$
-        procedure1 += "end\n"; //$NON-NLS-1$
-        procedure1 += "select e1 from pm1.g1;\n"; //$NON-NLS-1$
-        procedure1 += "END"; //$NON-NLS-1$
-        
-        String expected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nSELECT e1 FROM pm1.g1;\nEND"; //$NON-NLS-1$
-        
-        helpTestRewriteCommand(procedure1, expected);
-    }
-    
-    @Test public void testRewriteDeclare() {
-        String procedure1 = "CREATE virtual PROCEDURE  "; //$NON-NLS-1$
-        procedure1 += "BEGIN\n"; //$NON-NLS-1$
-        procedure1 += "declare integer x = 1 + 1;\n"; //$NON-NLS-1$
-        procedure1 += "END"; //$NON-NLS-1$
-        
-        String expected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nDECLARE integer x = 2;\nEND"; //$NON-NLS-1$
-        
-        helpTestRewriteCommand(procedure1, expected);
-    }
-      
-    @Test public void testRewriteUnionJoin() {
-        String sql = "select pm1.g1.e1 from pm1.g1 union join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
-        String expected = "SELECT pm1.g1.e1 FROM pm1.g1 FULL OUTER JOIN pm1.g2 ON 1 = 0 WHERE g1.e1 = '1'"; //$NON-NLS-1$
-                
-        helpTestRewriteCommand(sql, expected);        
-    }
-
-    @Test public void testRewriteNonNullDependentFunction() {
-        helpTestRewriteCriteria("pm1.g1.e1 = concat(null, pm1.g1.e2)", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteInWithNull() {
-        helpTestRewriteCriteria("convert(null, string) in (pm1.g1.e1, pm1.g1.e2)", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteXMLCriteriaCases5630And5640() {
-        helpTestRewriteCommand("select * from xmltest.doc1 where node1 = null", "SELECT * FROM xmltest.doc1 WHERE null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCorrelatedSubqueryInHaving() {
-        String sql = "select pm1.g1.e1 from pm1.g1 group by pm1.g1.e1 having pm1.g1.e1 in (select pm1.g1.e1 from pm1.g2)"; //$NON-NLS-1$
-        String expected = "SELECT pm1.g1.e1 FROM pm1.g1 GROUP BY pm1.g1.e1 HAVING pm1.g1.e1 IN (SELECT pm1.g1.e1 FROM pm1.g2)"; //$NON-NLS-1$
-                
-        Query query = (Query)helpTestRewriteCommand(sql, expected);
-        
-        List<Reference> refs = new LinkedList<Reference>();
-        
-        CorrelatedReferenceCollectorVisitor.collectReferences(query, Arrays.asList(new GroupSymbol("pm1.g1")), refs);//$NON-NLS-1$
-        
-        assertEquals(1, refs.size());
-    }
-    
-    @Test public void testRewriteSelectInto() {
-        String sql = "select distinct pm1.g1.e1 into #temp from pm1.g1"; //$NON-NLS-1$
-        String expected = "INSERT INTO #temp (#TEMP.e1) SELECT DISTINCT pm1.g1.e1 FROM pm1.g1"; //$NON-NLS-1$
-                
-        helpTestRewriteCommand(sql, expected);        
-    }
-    
-    /**
-     * Accounts for type change with duplicate names
-     */
-    @Test public void testRewriteSelectInto1() {
-        String sql = "select distinct e2, e2, e3, e4 into pm1.g1 from pm1.g2"; //$NON-NLS-1$
-        String expected = "INSERT INTO pm1.g1 (pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4) SELECT PM1_G1_1.e2 AS e1, PM1_G1_1.E2_0 AS e2, PM1_G1_1.e3, PM1_G1_1.e4 FROM (SELECT DISTINCT e2, e2 AS E2_0, e3, e4 FROM pm1.g2) AS pm1_g1_1"; //$NON-NLS-1$
-                
-        helpTestRewriteCommand(sql, expected);        
-    }
-    
-    @Test public void testUnionQueryNullInOneBranch() throws Exception {
-        verifyProjectedTypesOnUnionBranches("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
-                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
-    }
-    
-    @Test public void testUnionQueryNullInOneBranch2() throws Exception {
-        verifyProjectedTypesOnUnionBranches("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e1, e2 FROM pm1.g2 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
-                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
-    }
-
-    @Test public void testUnionQueryNullInOneBranch3() throws Exception {
-        verifyProjectedTypesOnUnionBranches("SELECT e1, null FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g2", //$NON-NLS-1$
-                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
-    }
-
-    @Test public void testUnionQueryNullInAllBranches() throws Exception {
-        verifyProjectedTypesOnUnionBranches("SELECT e1, null FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
-                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
-    }
-    
-    @Test public void testUnionQueryWithTypeConversion() throws Exception {
-        verifyProjectedTypesOnUnionBranches("SELECT e1 FROM pm1.g1 UNION ALL SELECT e2 FROM pm1.g2", //$NON-NLS-1$
-                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING});
-    }
-
-    private void verifyProjectedTypesOnUnionBranches(String unionQuery, Class<?>[] types) throws TeiidComponentException, TeiidProcessingException {
-        SetQuery union = (SetQuery)QueryParser.getQueryParser().parseCommand(unionQuery);
-        QueryResolver.resolveCommand(union, FakeMetadataFactory.example1Cached());
-        
-        union = (SetQuery)QueryRewriter.rewrite(union, FakeMetadataFactory.example1Cached(), null);
-        
-        for (QueryCommand query : union.getQueryCommands()) {
-            List<SingleElementSymbol> projSymbols = query.getProjectedSymbols();
-            for(int i=0; i<projSymbols.size(); i++) {
-                assertEquals("Found type mismatch at column " + i, types[i], projSymbols.get(i).getType()); //$NON-NLS-1$
-            }                
-        }
-    }
-        
-    /**
-     * The rewrite creates inline view to do the type conversion.
-     * 
-     * It also ensures that all project symbols are uniquely named in the inline view
-     */
-    @Test public void testSelectIntoWithOrderByAndTypeConversion() throws Exception {
-        String procedure = "CREATE VIRTUAL PROCEDURE\n"; //$NON-NLS-1$
-        procedure += "BEGIN\n";       //$NON-NLS-1$
-        procedure += "CREATE local temporary table temp (x string, y integer, z integer);\n";       //$NON-NLS-1$
-        procedure += "Select pm1.g1.e2, 1 as x, 2 as x into temp from pm1.g1 order by pm1.g1.e2 limit 1;\n"; //$NON-NLS-1$
-        procedure += "Select x from temp;\n"; //$NON-NLS-1$
-        procedure += "END\n"; //$NON-NLS-1$
-        
-        helpTestRewriteCommand(procedure, "CREATE VIRTUAL PROCEDURE\nBEGIN\nCREATE LOCAL TEMPORARY TABLE temp (x string, y integer, z integer);\nINSERT INTO temp (TEMP.x, TEMP.y, TEMP.z) SELECT TEMP_1.e2 AS x, TEMP_1.x AS y, TEMP_1.X_0 AS z FROM (SELECT pm1.g1.e2, 1 AS x, 2 AS X_0 FROM pm1.g1 ORDER BY pm1.g1.e2 LIMIT 1) AS temp_1;\nSELECT x FROM temp;\nEND"); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteNot() {
-        helpTestRewriteCriteria("not(not(pm1.g1.e1 = 1 + 1))", "pm1.g1.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteQueryWithNoFrom() {
-        String sql = "select 1 as a order by a"; //$NON-NLS-1$
-        
-        helpTestRewriteCommand(sql, "SELECT 1 AS a"); //$NON-NLS-1$
-    }
-        
-    /**
-     * Case 4814
-     */
-    @Test public void testVirtualRightOuterJoinSwap() throws Exception {
-        String sql = "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (select * from BQT1.smalla) sa RIGHT OUTER JOIN (select BQT1.mediumb.intkey from BQT1.mediumb) mb ON sa.IntKey = mb.IntKey"; //$NON-NLS-1$
-        helpTestRewriteCommand(sql, "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (SELECT BQT1.mediumb.intkey FROM BQT1.mediumb) AS mb LEFT OUTER JOIN (SELECT * FROM BQT1.smalla) AS sa ON sa.IntKey = mb.IntKey", FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
-    }
-    
-    /**
-     * Case 4814
-     */
-    @Test public void testVirtualRightOuterJoinSwap1() throws Exception {
-        String sql = "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM ((select * from BQT1.smalla) sa inner join BQT1.smallb on sa.intkey = smallb.intkey) RIGHT OUTER JOIN (select BQT1.mediumb.intkey from BQT1.mediumb) mb ON sa.IntKey = mb.IntKey"; //$NON-NLS-1$
-        helpTestRewriteCommand(sql, "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (SELECT BQT1.mediumb.intkey FROM BQT1.mediumb) AS mb LEFT OUTER JOIN ((SELECT * FROM BQT1.smalla) AS sa INNER JOIN BQT1.smallb ON sa.intkey = smallb.intkey) ON sa.IntKey = mb.IntKey", FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteConcat2() {
-        helpTestRewriteCriteria("concat2('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteConcat2_1() {
-        helpTestRewriteCriteria("concat2(null, null) is null", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteConcat2_2() throws Exception {
-        helpTestRewriteCriteria("concat2(pm1.g1.e1, null) = 'xyz'", "CASE WHEN pm1.g1.e1 IS NULL THEN null ELSE concat(ifnull(pm1.g1.e1, ''), '') END = 'xyz'", true); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteConcat2_3() throws Exception {
-        helpTestRewriteCriteria("concat2(pm1.g1.e1, convert(pm1.g1.e2, string)) = 'xyz'", "CASE WHEN (pm1.g1.e1 IS NULL) AND (convert(pm1.g1.e2, string) IS NULL) THEN null ELSE concat(ifnull(pm1.g1.e1, ''), ifnull(convert(pm1.g1.e2, string), '')) END = 'xyz'", true); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testRewriteConcat2_4() throws Exception {
-        helpTestRewriteCriteria("concat2('a', pm1.g1.e1) = 'xyz'", "concat('a', ifnull(pm1.g1.e1, '')) = 'xyz'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewiteEvaluatableAggregate() {
-    	helpTestRewriteCommand("select pm1.g1.e1, max(1) from pm1.g1", "SELECT pm1.g1.e1, 1 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteFromUnixTime() throws Exception {
-    	TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$
-    	try {
-    		helpTestRewriteCriteria("from_unixtime(pm1.g1.e2) = '1992-12-01 07:00:00'", "timestampadd(SQL_TSI_SECOND, pm1.g1.e2, {ts'1969-12-31 18:00:00.0'}) = {ts'1992-12-01 07:00:00.0'}"); //$NON-NLS-1$ //$NON-NLS-2$
-    	} finally {
-    		TimestampWithTimezone.resetCalendar(null);
-    	}
-    }
-    
-    @Test public void testRewriteNullIf() throws Exception {
-    	helpTestRewriteCriteria("nullif(pm1.g1.e2, pm1.g1.e4) = 1", "CASE WHEN pm1.g1.e2 = pm1.g1.e4 THEN convert(null, double) ELSE pm1.g1.e2 END = 1.0", true); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testRewriteCoalesce() throws Exception {
-    	helpTestRewriteCriteria("coalesce(convert(pm1.g1.e2, double), pm1.g1.e4) = 1", "ifnull(convert(pm1.g1.e2, double), pm1.g1.e4) = 1", true); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /**
-     * Test <code>QueryRewriter</code>'s ability to rewrite a query that 
-     * contains an aggregate function which uses a <code>CASE</code> 
-     * expression which contains <code>BETWEEN</code> criteria as its value.
-     * <p>
-     * An aggregate function list is defined and queries are created that 
-     * use each function from the list.  The list includes:
-     * <p>
-     * "SUM", "MAX", "MIN", "AVG", "COUNT"   
-     * <p>
-     * It is expected that the BETWEEN expression will be rewritten as 
-     * <code>CompoundCriteria</code>.
-     * <p>
-     * <table>
-     * <tr><th align="left" colspan=2>For example:
-     * <tr><td width="10*"><td>SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 
-     * THEN e2 ELSE -1 END) FROM pm1.g1
-     * <tr><th align="left" colspan=2>Is rewritten as:
-     * <tr><td width="10*"><td>SELECT SUM(CASE WHEN (e2 >= 3) AND (e2 <= 5) 
-     * THEN e2 ELSE -1 END) FROM pm1.g1
-     * </table>
-     * 
-     * @see org.teiid.query.rewriter.QueryRewriter
-     * @see org.teiid.query.sql.lang.BetweenCriteria
-     * @see org.teiid.query.sql.lang.CompoundCriteria
-     * @see org.teiid.query.sql.symbol.AggregateSymbol
-     * @see org.teiid.query.sql.symbol.SearchedCaseExpression
-     */
-    @Test public void testAggregateWithBetweenInCaseInSelect() {
-    	// Define a list of aggregates to test against
-    	List<String> aggregateCommands = Arrays.asList( new String[] { "SUM", "MAX", "MIN", "AVG", "COUNT" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-    	
-    	// Define a query and the expected rewritten query
-    	// ?AGGREGATE? represents the string substitution for an aggregate from aggregateCommands
-    	String sqlBefore = "SELECT ?AGGREGATE?(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
-    	String sqlAfter  = "SELECT ?AGGREGATE?(CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
-
-    	// Iterate through the aggregateCommands
-    	for ( String aCmd : aggregateCommands ) {
-    		// Replace ?AGGREGATE? with the command from aggregateCommands
-    		String sql = sqlBefore.replace("?AGGREGATE?", aCmd); //$NON-NLS-1$
-    		String exSql = sqlAfter.replace("?AGGREGATE?", aCmd); //$NON-NLS-1$
-    		// Test QueryRewriter
-        	Command cmd = helpTestRewriteCommand( sql, exSql );
-        	// Check the rewritten command to verify that CompundCriteria replaced BetweenCriteria
-        	CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((ExpressionSymbol) cmd.getProjectedSymbols().get(0)).getExpression()).getWhen().get(0);
-        	assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
-        	assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
-    	}
-    }
-    
-    /**
-     * Test <code>QueryRewriter</code>'s ability to rewrite a query that 
-     * contains a <code>CASE</code> expression which contains 
-     * <code>BETWEEN</code> criteria in the queries <code>SELECT</code> clause.
-     * <p>
-     * It is expected that the BETWEEN expression will be rewritten as 
-     * <code>CompoundCriteria</code>.
-     * <p>
-     * <table>
-     * <tr><th align="left" colspan=2>For example:
-     * <tr><td width="10*"><td>SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 
-     * ELSE -1 END FROM pm1.g1 
-     * <tr><th align="left" colspan=2>Is rewritten as:
-     * <tr><td width="10*"><td>SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 
-     * ELSE -1 END FROM pm1.g1
-     * </table>
-     * 
-     * @see org.teiid.query.rewriter.QueryRewriter
-     * @see org.teiid.query.sql.lang.BetweenCriteria
-     * @see org.teiid.query.sql.lang.CompoundCriteria
-     * @see org.teiid.query.sql.symbol.SearchedCaseExpression
-     */
-    @Test public void testBetweenInCaseInSelect() {
-    	String sqlBefore = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
-    	String sqlAfter = "SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
-    	
-    	Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
-    	CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((ExpressionSymbol) cmd.getProjectedSymbols().get(0)).getExpression()).getWhen().get(0);
-    	assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
-    	assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
-    }
-    
-    /**
-     * Test <code>QueryRewriter</code>'s ability to rewrite a query that 
-     * contains a <code>CASE</code> expression which contains 
-     * <code>BETWEEN</code> criteria in the queries <code>WHERE</code> clause.
-     * <p>
-     * It is expected that the BETWEEN expression will be rewritten as 
-     * <code>CompoundCriteria</code>.
-     * <p>
-     * <table>
-     * <tr><th align="left" colspan=2>For example:
-     * <tr><td width="10*"><td>SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 
-     * BETWEEN 3 AND 5 THEN e2 ELSE -1 END 
-     * <tr><th align="left" colspan=2>Is rewritten as:
-     * <tr><td width="10*"><td>SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN  
-     * (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END
-     * </table>
-     * 
-     * @see org.teiid.query.rewriter.QueryRewriter
-     * @see org.teiid.query.sql.lang.BetweenCriteria
-     * @see org.teiid.query.sql.lang.CompoundCriteria
-     * @see org.teiid.query.sql.symbol.SearchedCaseExpression
-     */
-    @Test public void testBetweenInCase() {
-    	String sqlBefore = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END"; //$NON-NLS-1$
-    	String sqlAfter = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END"; //$NON-NLS-1$
-    	
-    	Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
-    	CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((CompareCriteria) ((Query) cmd).getCriteria()).getRightExpression()).getWhen().get(0);
-    	assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
-    	assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteNullHandling() {
-    	String original = "pm1.g1.e1 like '%'"; //$NON-NLS-1$
-    	String expected = "pm1.g1.e1 is not null"; //$NON-NLS-1$
-    	
-    	helpTestRewriteCriteria(original, expected);
-    }
-    
-    @Test public void testRewriteNullHandling1() {
-    	String original = "not(pm1.g1.e1 like '%' or pm1.g1.e1 = '1')"; //$NON-NLS-1$
-    	String expected = "1 = 0"; //$NON-NLS-1$
-    	
-    	helpTestRewriteCriteria(original, expected);
-    }
-    
-    @Test public void testRewriteNullHandling2() {
-    	String original = "not(pm1.g1.e1 like '%' and pm1.g1.e1 = '1')"; //$NON-NLS-1$
-    	String expected = "pm1.g1.e1 <> '1'"; //$NON-NLS-1$
-    	
-    	helpTestRewriteCriteria(original, expected);
-    }
-    
-    @Test public void testRewriteNullHandling3() {
-    	String original = "pm1.g1.e1 like '%' or pm1.g1.e1 = '1'"; //$NON-NLS-1$
-    	String expected = "(pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e1 = '1')"; //$NON-NLS-1$
-    	
-    	helpTestRewriteCriteria(original, expected);
-    }
-    
-    @Test public void testRewriteNullHandling4() {
-    	String original = "not((pm1.g1.e1 like '%' or pm1.g1.e1 = '1') and pm1.g1.e2 < 5)"; //$NON-NLS-1$
-    	String expected = "(pm1.g1.e2 < 5) AND ((pm1.g1.e2 < 5) OR (pm1.g1.e1 <> '1'))"; //$NON-NLS-1$
-    	
-    	helpTestRewriteCriteria(original, expected);
-    }
-    
-    @Test public void testRewriteNullHandling5() {
-    	String original = "not(pm1.g1.e1 not like '%' and pm1.g1.e3 = '1') or pm1.g1.e2 < 5"; //$NON-NLS-1$
-    	String expected = "(pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e3 <> TRUE) OR (pm1.g1.e2 < 5)"; //$NON-NLS-1$
-    	
-    	helpTestRewriteCriteria(original, expected);
-    }
-    
-    @Test public void testRewriteChar() {
-    	String original = "convert(pm1.g1.e1, char) = '100'"; //$NON-NLS-1$
-    	String expected = "1 = 0"; //$NON-NLS-1$
-    	
-    	helpTestRewriteCriteria(original, expected);
-    }
-    
-    /**
-     * Test ensures that '22.0' is a valid long via bigdecimal
-     */
-    @Test public void testRewriteBigDecimal() {
-    	String original = "convert(BQT1.SmallA.LongNum, bigdecimal) = '22.0'"; //$NON-NLS-1$
-    	CompareCriteria crit = new CompareCriteria(new ElementSymbol("BQT1.SmallA.LongNum"), CompareCriteria.EQ, new Constant(new Long(22))); //$NON-NLS-1$
-    	helpTestRewriteCriteria(original, crit, FakeMetadataFactory.exampleBQTCached()); 
-    }
-
-    /**
-     * Test ensures that we will not attempt to invert the widening conversion
-     */
-    @Test public void testRewriteWideningIn() {
-    	String original = "convert(BQT1.SmallA.TimestampValue, time) in ({t'10:00:00'}, {t'11:00:00'})"; //$NON-NLS-1$
-    	helpTestRewriteCriteria(original, parseCriteria("convert(BQT1.SmallA.TimestampValue, time) in ({t'10:00:00'}, {t'11:00:00'})", FakeMetadataFactory.exampleBQTCached()), FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testRewriteParseDate() {
-    	String original = "parsedate(BQT1.SmallA.stringkey, 'yymmdd') = {d'1970-01-01'}"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-    	helpTestRewriteCriteria(original, parseCriteria("convert(parsetimestamp(BQT1.SmallA.stringkey, 'yymmdd'), date) = {d'1970-01-01'}", metadata), metadata); //$NON-NLS-1$
-    }
-
-    @Test public void testRewriteFormatTime() {
-    	String original = "formattime(BQT1.SmallA.timevalue, 'hh:mm') = '08:02'"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-    	helpTestRewriteCriteria(original, parseCriteria("formattimestamp(convert(BQT1.SmallA.timevalue, timestamp), 'hh:mm') = '08:02'", metadata), metadata); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteTimestampAdd() {
-    	String original = "timestampadd(SQL_TSI_SECOND, 1, BQT1.SmallA.timevalue) = {t'08:02:00'}"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-    	helpTestRewriteCriteria(original, parseCriteria("convert(timestampadd(SQL_TSI_SECOND, 1, convert(BQT1.SmallA.timevalue, timestamp)), time) = {t'08:02:00'}", metadata), metadata); //$NON-NLS-1$
-    }
-    
-    @Test public void testRewriteXmlElement() throws Exception {
-    	String original = "xmlserialize(document xmlelement(name a, xmlattributes('b' as c)) as string)"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-    	helpTestRewriteExpression(original, "'<a c=\"b\"></a>'", metadata);
-    }
-    
-    @Test public void testRewriteXmlElement1() throws Exception {
-    	String original = "xmlelement(name a, xmlattributes(1+1 as c), BQT1.SmallA.timevalue)"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-    	helpTestRewriteExpression(original, "XMLELEMENT(NAME a, XMLATTRIBUTES(2 AS c), BQT1.SmallA.timevalue)", metadata);
-    }
-    
-    @Test public void testRewriteXmlSerialize() throws Exception {
-    	String original = "xmlserialize(document xmlelement(name a, xmlattributes('b' as c)) as string)"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-    	helpTestRewriteExpression(original, "'<a c=\"b\"></a>'", metadata);
-    }
-    
-    @Test public void testRewriteXmlTable() throws Exception {
-    	String original = "select * from xmltable('/' passing 1 + 1 as a columns x string default curdate()) as x"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-    	helpTestRewriteCommand(original, "SELECT * FROM XMLTABLE('/' PASSING 2 AS a COLUMNS x string DEFAULT curdate()) AS x", metadata);
-    }
-    
-    @Test public void testRewriteQueryString() throws Exception {
-    	String original = "querystring('path', 'value' as \"&x\", ' & ' as y, null as z)"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-    	helpTestRewriteExpression(original, "'path?%26x=value&y=%20%26%20'", metadata);
-    }
-    
-    @Test public void testRewriteExpressionCriteria() throws Exception {
-    	helpTestRewriteCriteria("pm1.g1.e3", "pm1.g1.e3 = true");
-    }
-
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java (from rev 2707, branches/7.2.x/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,2325 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.rewriter;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.TimestampWithTimezone;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.util.ResolverVisitor;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.ExpressionSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.SearchedCaseExpression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
+import org.teiid.query.unittest.FakeMetadataFacade;
+import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.util.ContextProperties;
+
+
+ at SuppressWarnings("nls")
+public class TestQueryRewriter {
+
+    private static final String TRUE_STR = "1 = 1"; //$NON-NLS-1$
+    private static final String FALSE_STR = "1 = 0"; //$NON-NLS-1$
+
+    // ################################## TEST HELPERS ################################
+    
+    private Criteria parseCriteria(String critStr, QueryMetadataInterface metadata) {
+        try {
+            Criteria crit = QueryParser.getQueryParser().parseCriteria(critStr);
+            
+            // resolve against metadata
+            QueryResolver.resolveCriteria(crit, metadata);
+            
+            return crit;
+        } catch(TeiidException e) {
+            throw new RuntimeException(e);
+        }   
+    }
+    
+    private Criteria helpTestRewriteCriteria(String original, String expected) {
+        try {
+            return helpTestRewriteCriteria(original, expected, false);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } 
+    }   
+    
+    private Criteria helpTestRewriteCriteria(String original, String expected, boolean rewrite) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        Criteria expectedCrit = parseCriteria(expected, metadata);
+        if (rewrite) {
+            QueryResolver.resolveCriteria(expectedCrit, metadata);
+            expectedCrit = QueryRewriter.rewriteCriteria(expectedCrit, null, null, metadata);
+        }
+        return helpTestRewriteCriteria(original, expectedCrit, metadata);
+    }
+
+    private Criteria helpTestRewriteCriteria(String original, Criteria expectedCrit, QueryMetadataInterface metadata) {
+        Criteria origCrit = parseCriteria(original, metadata);
+        
+        Criteria actual = null;
+        // rewrite
+        try { 
+            actual = QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
+            assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
+        }
+        return actual;
+    }  
+    
+    private Expression helpTestRewriteExpression(String original, String expected, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
+    	Expression actualExp = QueryParser.getQueryParser().parseExpression(original);
+    	ResolverVisitor.resolveLanguageObject(actualExp, metadata);
+    	CommandContext context = new CommandContext();
+    	context.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+    	actualExp = QueryRewriter.rewriteExpression(actualExp, null, context, metadata);
+    	if (expected != null) {
+	    	Expression expectedExp = QueryParser.getQueryParser().parseExpression(expected);
+	    	ResolverVisitor.resolveLanguageObject(expectedExp, metadata);
+	    	assertEquals(expectedExp, actualExp);
+    	}
+    	return actualExp;
+    }
+    
+	private String getRewritenProcedure(String procedure, String userUpdateStr, String procedureType) throws TeiidComponentException, TeiidProcessingException {
+        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
+
+        return getRewritenProcedure(userUpdateStr, metadata);
+	}
+
+	private String getRewritenProcedure(String userUpdateStr,
+			QueryMetadataInterface metadata) throws TeiidComponentException,
+			QueryMetadataException, TeiidProcessingException {
+		ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr); 
+        QueryResolver.resolveCommand(userCommand, metadata);
+        CreateUpdateProcedureCommand proc = (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, null);
+		QueryRewriter.rewrite(userCommand, metadata, null);
+		Command result = QueryRewriter.rewrite(proc, metadata, null);
+		return result.toString();
+	}
+	
+    static Command helpTestRewriteCommand(String original, String expected) { 
+        try {
+            return helpTestRewriteCommand(original, expected, FakeMetadataFactory.example1Cached());
+        } catch(TeiidException e) { 
+            throw new TeiidRuntimeException(e);
+        }
+    }
+    
+    static Command helpTestRewriteCommand(String original, String expected, QueryMetadataInterface metadata) throws TeiidException { 
+        Command command = QueryParser.getQueryParser().parseCommand(original);            
+        QueryResolver.resolveCommand(command, metadata);
+        Command rewriteCommand = QueryRewriter.rewrite(command, metadata, null);
+        assertEquals("Rewritten command was not expected", expected, rewriteCommand.toString()); //$NON-NLS-1$
+        return rewriteCommand;
+    }
+    
+    @Test public void testRewriteUnknown() {
+        helpTestRewriteCriteria("pm1.g1.e1 = '1' and '1' = convert(null, string)", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteUnknown1() {
+        helpTestRewriteCriteria("pm1.g1.e1 = '1' or '1' = convert(null, string)", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteUnknown2() {
+        helpTestRewriteCriteria("not('1' = convert(null, string))", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteUnknown3() {
+        helpTestRewriteCriteria("pm1.g1.e1 like convert(null, string))", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteUnknown4() {
+        helpTestRewriteCriteria("null in ('a', 'b', 'c')", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteUnknown5() {
+        helpTestRewriteCriteria("(null <> null) and 1 = 0", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteUnknown6() {
+        helpTestRewriteCriteria("not(pm1.g1.e1 = '1' and '1' = convert(null, string))", "pm1.g1.e1 <> '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+        
+    @Test public void testRewriteUnknown7() {
+        helpTestRewriteCriteria("not(pm1.g1.e1 = '1' or '1' = convert(null, string))", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteUnknown8() {
+        helpTestRewriteCriteria("pm1.g1.e1 in (2, null)", "pm1.g1.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$ 
+    }
+    
+    @Test public void testRewriteInCriteriaWithRepeats() {
+        helpTestRewriteCriteria("pm1.g1.e1 in ('1', '1', '2')", "pm1.g1.e1 IN ('1', '2')"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteInCriteriaWithSingleValue() {
+        helpTestRewriteCriteria("pm1.g1.e1 in ('1')", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteInCriteriaWithSingleValue1() {
+        helpTestRewriteCriteria("pm1.g1.e1 not in ('1')", "pm1.g1.e1 != '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteInCriteriaWithConvert() {
+        helpTestRewriteCriteria("convert(pm1.g1.e2, string) not in ('x')", "pm1.g1.e2 IS NOT NULL"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteInCriteriaWithNoValues() throws Exception {
+    	ElementSymbol e1 = new ElementSymbol("e1");
+    	e1.setGroupSymbol(new GroupSymbol("g1"));
+        Criteria crit = new SetCriteria(e1, Collections.EMPTY_LIST); //$NON-NLS-1$
+        
+        Criteria actual = QueryRewriter.rewriteCriteria(crit, null, null, null);
+        
+        IsNullCriteria inc = new IsNullCriteria(e1);
+        inc.setNegated(true);
+        assertEquals(inc, actual);
+    }
+        
+    @Test public void testRewriteBetweenCriteria1() {
+        helpTestRewriteCriteria("pm1.g1.e1 BETWEEN 1000 AND 2000", "(pm1.g1.e1 >= '1000') AND (pm1.g1.e1 <= '2000')"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteBetweenCriteria2() {
+        helpTestRewriteCriteria("pm1.g1.e1 NOT BETWEEN 1000 AND 2000", "(pm1.g1.e1 < '1000') OR (pm1.g1.e1 > '2000')"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCrit1() {
+        helpTestRewriteCriteria("concat('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCrit2() {
+        helpTestRewriteCriteria("'x' = pm1.g1.e1", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCrit3() {
+        helpTestRewriteCriteria("pm1.g1.e1 = convert('a', string)", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCrit4() {
+        helpTestRewriteCriteria("pm1.g1.e1 = CONVERT('a', string)", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCrit5() {
+        helpTestRewriteCriteria("pm1.g1.e1 in ('a')", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit6() {
+        helpTestRewriteCriteria("1 = convert(pm1.g1.e1,integer) + 10", "pm1.g1.e1 = '-9'"); //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+    
+    @Test public void testRewriteCrit7() {
+        helpTestRewriteCriteria("((pm1.g1.e1 = 1) and (pm1.g1.e1 = 1))", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteMatchCritEscapeChar1() {
+        helpTestRewriteCriteria("pm1.g1.e1 LIKE 'x_' ESCAPE '\\'", "pm1.g1.e1 LIKE 'x_'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteMatchCritEscapeChar2() {
+        helpTestRewriteCriteria("pm1.g1.e1 LIKE '#%x' ESCAPE '#'", "pm1.g1.e1 LIKE '#%x' ESCAPE '#'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteMatchCritEscapeChar3() {
+        helpTestRewriteCriteria("pm1.g1.e1 LIKE '#%x'", "pm1.g1.e1 LIKE '#%x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteMatchCritEscapeChar4() {
+        helpTestRewriteCriteria("pm1.g1.e1 LIKE pm1.g1.e1 ESCAPE '#'", "pm1.g1.e1 LIKE pm1.g1.e1 ESCAPE '#'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteMatchCritEscapeChar5() throws Exception {
+        MatchCriteria mcrit = new MatchCriteria(new ElementSymbol("pm1.g1.e1"), new Constant(null, DataTypeManager.DefaultDataClasses.STRING), '#'); //$NON-NLS-1$
+        Criteria expected = QueryRewriter.UNKNOWN_CRITERIA; 
+                
+        Object actual = QueryRewriter.rewriteCriteria(mcrit, null, null, null); 
+        assertEquals("Did not get expected rewritten criteria", expected, actual); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteMatchCrit1() {
+        helpTestRewriteCriteria("pm1.g1.e1 LIKE 'x' ESCAPE '\\'", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteMatchCrit2() {
+        helpTestRewriteCriteria("pm1.g1.e1 NOT LIKE 'x'", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteMatchCrit3() {
+        helpTestRewriteCriteria("pm1.g1.e1 NOT LIKE '%'", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCritTimestampCreate1() {
+        helpTestRewriteCriteria("timestampCreate(pm3.g1.e2, pm3.g1.e3) = {ts'2004-11-23 09:25:00'}", "(pm3.g1.e2 = {d'2004-11-23'}) AND (pm3.g1.e3 = {t'09:25:00'})"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritTimestampCreate2() {
+        helpTestRewriteCriteria("{ts'2004-11-23 09:25:00'} = timestampCreate(pm3.g1.e2, pm3.g1.e3)", "(pm3.g1.e2 = {d'2004-11-23'}) AND (pm3.g1.e3 = {t'09:25:00'})"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritSwap1() {
+        helpTestRewriteCriteria("'x' = pm1.g1.e1", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritSwap2() {
+        helpTestRewriteCriteria("'x' <> pm1.g1.e1", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritSwap3() {
+        helpTestRewriteCriteria("'x' < pm1.g1.e1", "pm1.g1.e1 > 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritSwap4() {
+        helpTestRewriteCriteria("'x' <= pm1.g1.e1", "pm1.g1.e1 >= 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritSwap5() {
+        helpTestRewriteCriteria("'x' > pm1.g1.e1", "pm1.g1.e1 < 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritSwap6() {
+        helpTestRewriteCriteria("'x' >= pm1.g1.e1", "pm1.g1.e1 <= 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritExpr_op1() {
+        helpTestRewriteCriteria("pm1.g1.e2 + 5 = 10", "pm1.g1.e2 = 5"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritExpr_op2() {
+        helpTestRewriteCriteria("pm1.g1.e2 - 5 = 10", "pm1.g1.e2 = 15"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritExpr_op3() {
+        helpTestRewriteCriteria("pm1.g1.e2 * 5 = 10", "pm1.g1.e2 = 2"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritExpr_op4() {
+        helpTestRewriteCriteria("pm1.g1.e2 / 5 = 10", "pm1.g1.e2 = 50"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritExpr_signFlip1() {
+        helpTestRewriteCriteria("pm1.g1.e2 * -5 > 10", "pm1.g1.e2 < -2"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritExpr_signFlip2() {
+        helpTestRewriteCriteria("pm1.g1.e2 * -5 >= 10", "pm1.g1.e2 <= -2"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCritExpr_signFlip3() {
+        helpTestRewriteCriteria("pm1.g1.e2 * -5 < 10", "pm1.g1.e2 > -2"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritExpr_signFlip4() {
+        helpTestRewriteCriteria("pm1.g1.e2 * -5 <= 10", "pm1.g1.e2 >= -2"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCritExpr_backwards1() {
+        helpTestRewriteCriteria("5 + pm1.g1.e2 <= 10", "pm1.g1.e2 <= 5"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritExpr_backwards2() {
+        helpTestRewriteCriteria("-5 * pm1.g1.e2 <= 10", "pm1.g1.e2 >= -2"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCritExpr_unhandled1() {
+        helpTestRewriteCriteria("5 / pm1.g1.e2 <= 10", "5 / pm1.g1.e2 <= 10"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCritExpr_unhandled2() {
+        helpTestRewriteCriteria("5 - pm1.g1.e2 <= 10", "5 - pm1.g1.e2 <= 10"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseDate() {
+        helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMMdd') = {d'2003-05-01'}", //$NON-NLS-1$
+                                "pm3.g1.e1 = '20030501'" );         //$NON-NLS-1$
+    }
+    
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseDate1() {
+        helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMM') = {d'2003-05-01'}", //$NON-NLS-1$
+                                "pm3.g1.e1 = '200305'" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="we're no longer considering parsedate directly")
+    @Test public void testRewriteCrit_parseDate2() {
+        helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMM') = {d'2003-05-02'}", //$NON-NLS-1$
+                                "1 = 0" );         //$NON-NLS-1$
+    }
+    
+    @Ignore(value="Should be moved to the validator")
+    @Test public void testRewriteCrit_invalidParseDate() {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        Criteria origCrit = parseCriteria("PARSEDATE(pm3.g1.e1, '''') = {d'2003-05-01'}", metadata); //$NON-NLS-1$
+        
+        try { 
+            QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+            fail("Expected failure"); //$NON-NLS-1$
+        } catch(TeiidException e) { 
+            assertEquals("Error Code:ERR.015.001.0003 Message:Error simplifying criteria: PARSEDATE(pm3.g1.e1, '''') = {d'2003-05-01'}", e.getMessage());     //$NON-NLS-1$
+        }
+    }
+    
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseTime() {
+        helpTestRewriteCriteria("PARSETIME(pm3.g1.e1, 'HH mm ss') = {t'13:25:04'}", //$NON-NLS-1$
+                                "pm3.g1.e1 = '13 25 04'" );         //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteCrit_parseTimestamp() {
+        helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') = {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
+                                "1 = 0" );         //$NON-NLS-1$
+    }
+    
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseTimestamp1() {
+        helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') = {ts'2003-01-01 00:25:00.0'}", //$NON-NLS-1$
+                                "pm3.g1.e1 = '2003 01 25'" );         //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCrit_parseTimestamp2() {
+        helpTestRewriteCriteria("PARSETimestamp(CONVERT(pm3.g1.e2, string), 'yyyy-MM-dd') = {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
+                                "1 = 0" );         //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteCrit_parseTimestamp3() {
+        helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') <> {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
+                                "pm3.g1.e1 is not null" );         //$NON-NLS-1$
+    }
+    
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseTimestamp4() {
+        helpTestRewriteCriteria("PARSETimestamp(CONVERT(pm3.g1.e2, string), 'yyyy-MM-dd') = {ts'2003-05-01 00:00:00.0'}", //$NON-NLS-1$
+                                "pm3.g1.e2 = {d'2003-05-01'}" );         //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCrit_parseTimestamp_notEquality() {
+        helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') > {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
+                                "PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') > {ts'2003-05-01 13:25:04.5'}" );         //$NON-NLS-1$
+    }
+    
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseTimestamp_decompose() {
+        helpTestRewriteCriteria("PARSETIMESTAMP(CONCAT(FORMATDATE(pm3.g1.e2, 'yyyyMMdd'), FORMATTIME(pm3.g1.e3, 'HHmmss')), 'yyyyMMddHHmmss') = PARSETIMESTAMP('19690920183045', 'yyyyMMddHHmmss')", //$NON-NLS-1$
+        "(pm3.g1.e2 = {d'1969-09-20'}) AND (pm3.g1.e3 = {t'18:30:45'})" );         //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCrit_timestampCreate_decompose() {
+        helpTestRewriteCriteria("timestampCreate(pm3.g1.e2, pm3.g1.e3) = PARSETIMESTAMP('19690920183045', 'yyyyMMddHHmmss')", //$NON-NLS-1$
+        "(pm3.g1.e2 = {d'1969-09-20'}) AND (pm3.g1.e3 = {t'18:30:45'})" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseInteger() {
+        helpTestRewriteCriteria("parseInteger(pm1.g1.e1, '#,##0') = 1234", //$NON-NLS-1$
+                                "pm1.g1.e1 = '1,234'" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseLong() {
+        helpTestRewriteCriteria("parseLong(pm1.g1.e1, '#,##0') = convert(1234, long)", //$NON-NLS-1$
+                                "pm1.g1.e1 = '1,234'" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseBigInteger() {
+        helpTestRewriteCriteria("parseBigInteger(pm1.g1.e1, '#,##0') = convert(1234, biginteger)", //$NON-NLS-1$
+                                "pm1.g1.e1 = '1,234'" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseFloat() {
+        helpTestRewriteCriteria("parseFloat(pm1.g1.e1, '#,##0.###') = convert(1234.123, float)", //$NON-NLS-1$
+                                "pm1.g1.e1 = '1,234.123'" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseDouble() {
+        helpTestRewriteCriteria("parseDouble(pm1.g1.e1, '$#,##0.00') = convert(1234.5, double)", //$NON-NLS-1$
+                                "pm1.g1.e1 = '$1,234.50'" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCrit_parseBigDecimal() {
+        helpTestRewriteCriteria("parseBigDecimal(pm1.g1.e1, '#,##0.###') = convert(1234.1234, bigdecimal)", //$NON-NLS-1$
+                                "pm1.g1.e1 = '1,234.123'" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatDate() {
+        helpTestRewriteCriteria("formatDate(pm3.g1.e2, 'yyyyMMdd') = '20030501'", //$NON-NLS-1$
+                                "pm3.g1.e2 = {d'2003-05-01'}" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatTime() {
+        helpTestRewriteCriteria("formatTime(pm3.g1.e3, 'HH mm ss') = '13 25 04'", //$NON-NLS-1$
+                                "pm3.g1.e3 = {t'13:25:04'}" );         //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteCrit_formatTimestamp() {
+        helpTestRewriteCriteria("formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss') = '05 01, 1974 - 07:00:00'", //$NON-NLS-1$
+                                "formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss') = '05 01, 1974 - 07:00:00'" );         //$NON-NLS-1$
+    }
+    
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatTimestamp1() {
+        helpTestRewriteCriteria("formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss.S') = '05 01, 1974 - 07:00:00.0'", //$NON-NLS-1$
+                                "pm3.g1.e4 = {ts'1974-05-01 07:00:00.0'}" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatInteger() {
+        helpTestRewriteCriteria("formatInteger(pm1.g1.e2, '#,##0') = '1,234'", //$NON-NLS-1$
+                                "pm1.g1.e2 = 1234" );         //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCrit_formatInteger1() {
+        helpTestRewriteCriteria("formatInteger(pm1.g1.e2, '#5') = '105'", //$NON-NLS-1$
+                                "formatInteger(pm1.g1.e2, '#5') = '105'" );         //$NON-NLS-1$
+    }
+
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatLong() {
+        helpTestRewriteCriteria("formatLong(convert(pm1.g1.e2, long), '#,##0') = '1,234,567,890,123'", //$NON-NLS-1$
+                                "1 = 0" );         //$NON-NLS-1$
+    }
+    
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatLong1() {
+        helpTestRewriteCriteria("formatLong(convert(pm1.g1.e2, long), '#,##0') = '1,234,567,890'", //$NON-NLS-1$
+                                "pm1.g1.e2 = 1234567890" );         //$NON-NLS-1$
+    }
+    
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatTimestampInvert() { 
+        String original = "formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss.S') = ?"; //$NON-NLS-1$ 
+        String expected = "pm3.g1.e4 = parseTimestamp(?, 'MM dd, yyyy - HH:mm:ss.S')"; //$NON-NLS-1$ 
+         
+        helpTestRewriteCriteria(original, expected); 
+    } 
+     
+    @Test public void testRewriteCrit_plusInvert() { 
+        String original = "pm1.g1.e2 + 1.1 = ?"; //$NON-NLS-1$ 
+        String expected = "pm1.g1.e2 = ? - 1.1"; //$NON-NLS-1$ 
+         
+        helpTestRewriteCriteria(original, expected);
+    } 
+
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatBigInteger() throws Exception {
+        String original = "formatBigInteger(convert(pm1.g1.e2, biginteger), '#,##0') = '1,234,567,890'"; //$NON-NLS-1$
+        String expected = "pm1.g1.e2 = 1234567890"; //$NON-NLS-1$
+        
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        Criteria origCrit = parseCriteria(original, metadata);
+        Criteria expectedCrit = parseCriteria(expected, metadata);
+        
+        // rewrite
+        Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+        assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
+    }
+
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatFloat() throws Exception {
+        String original = "formatFloat(convert(pm1.g1.e4, float), '#,##0.###') = '1,234.123'"; //$NON-NLS-1$
+        String expected = "pm1.g1.e4 = 1234.123046875"; //$NON-NLS-1$
+        
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        Criteria origCrit = parseCriteria(original, metadata);
+        
+        // rewrite
+        Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+        assertEquals("Did not rewrite correctly: ", expected, actual.toString()); //$NON-NLS-1$
+    }
+
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatDouble() throws Exception {
+        String original = "formatDouble(convert(pm1.g1.e4, double), '$#,##0.00') = '$1,234.50'"; //$NON-NLS-1$
+        String expected = "pm1.g1.e4 = '1234.5'"; //$NON-NLS-1$
+        
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        Criteria origCrit = parseCriteria(original, metadata);
+        Criteria expectedCrit = parseCriteria(expected, metadata);
+        ((CompareCriteria)expectedCrit).setRightExpression(new Constant(new Double(1234.5)));
+        
+        // rewrite
+        Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+        assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
+    }
+
+    @Ignore(value="Cannot deterime if the format is narrowing")
+    @Test public void testRewriteCrit_formatBigDecimal() throws Exception {
+        String original = "formatBigDecimal(convert(pm1.g1.e4, bigdecimal), '#,##0.###') = '1,234.5'"; //$NON-NLS-1$
+        String expected = "pm1.g1.e4 = 1234.5"; //$NON-NLS-1$
+        
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        Criteria origCrit = parseCriteria(original, metadata);
+        Criteria expectedCrit = parseCriteria(expected, metadata);
+        
+        // rewrite
+        Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+        assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCritTimestampDiffDate1() {
+        helpTestRewriteCriteria("timestampdiff(SQL_TSI_DAY, {d'2003-05-15'}, {d'2003-05-17'} ) = 2", TRUE_STR); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCritTimestampDiffDate2() {
+        helpTestRewriteCriteria("timestampdiff(SQL_TSI_DAY, {d'2003-06-02'}, {d'2003-05-17'} ) = -16", TRUE_STR); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCritTimestampDiffDate3() {
+        helpTestRewriteCriteria("timestampdiff(SQL_TSI_QUARTER, {d'2002-01-25'}, {d'2003-06-01'} ) = 5", TRUE_STR); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCritTimestampDiffTime1() {
+        helpTestRewriteCriteria("timestampdiff(SQL_TSI_HOUR, {t'03:04:45'}, {t'05:05:36'} ) = 2", TRUE_STR); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCritTimestampDiffTime1_ignorecase() {
+        helpTestRewriteCriteria("timestampdiff(SQL_tsi_HOUR, {t'03:04:45'}, {t'05:05:36'} ) = 2", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteOr1() {
+        helpTestRewriteCriteria("(5 = 5) OR (0 = 1)", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteOr2() {
+        helpTestRewriteCriteria("(0 = 1) OR (5 = 5)", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteOr3() {
+        helpTestRewriteCriteria("(1 = 1) OR (5 = 5)", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteOr4() {
+        helpTestRewriteCriteria("(0 = 1) OR (4 = 5)", FALSE_STR); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteOr5() {
+        helpTestRewriteCriteria("(0 = 1) OR (4 = 5) OR (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')");         //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteOr6() {
+        helpTestRewriteCriteria("(0 = 1) OR (4 = 5) OR (pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')", "(pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')");     //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteOr7() {
+        helpTestRewriteCriteria("(pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')", "(pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')");     //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteAnd1() {
+        helpTestRewriteCriteria("(5 = 5) AND (0 = 1)", FALSE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteAnd2() {
+        helpTestRewriteCriteria("(0 = 1) AND (5 = 5)", FALSE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteAnd3() {
+        helpTestRewriteCriteria("(1 = 1) AND (5 = 5)", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteAnd4() {
+        helpTestRewriteCriteria("(0 = 1) AND (4 = 5)", FALSE_STR); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteAnd5() { 
+        helpTestRewriteCriteria("(1 = 1) AND (5 = 5) AND (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')");             //$NON-NLS-1$ //$NON-NLS-2$
+    }
+ 
+    @Test public void testRewriteAnd6() { 
+        helpTestRewriteCriteria("(1 = 1) AND (5 = 5) AND (pm1.g1.e1 = 'x') and (pm1.g1.e1 = 'y')", "(pm1.g1.e1 = 'x') AND (pm1.g1.e1 = 'y')");             //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteAnd7() {
+        helpTestRewriteCriteria("(pm1.g1.e1 = 'x') AND (pm1.g1.e1 = 'y')", "(pm1.g1.e1 = 'x') AND (pm1.g1.e1 = 'y')");     //$NON-NLS-1$ //$NON-NLS-2$
+    }
+        
+    @Test public void testRewriteMixed1() {
+        helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed2() {
+        helpTestRewriteCriteria("((1=2) AND (1=1)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed3() {
+        helpTestRewriteCriteria("((1=1) AND (1=2)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed4() {
+        helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=2) AND (1=1))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed5() {
+        helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=1) AND (1=2))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed6() {
+        helpTestRewriteCriteria("((1=2) AND (1=1)) OR ((1=2) AND (1=1))", FALSE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed7() {
+        helpTestRewriteCriteria("((1=1) AND (1=2)) OR ((1=1) AND (1=2))", FALSE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed8() {
+        helpTestRewriteCriteria("((1=2) AND (1=2)) OR ((1=2) AND (1=2))", FALSE_STR); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteMixed9() {
+        helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed10() {
+        helpTestRewriteCriteria("((1=2) OR (1=1)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed11() {
+        helpTestRewriteCriteria("((1=1) OR (1=2)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed12() {
+        helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=2) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed13() {
+        helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=1) OR (1=2))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed14() {
+        helpTestRewriteCriteria("((1=2) OR (1=1)) AND ((1=2) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed15() {
+        helpTestRewriteCriteria("((1=1) OR (1=2)) AND ((1=1) OR (1=2))", TRUE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteMixed16() {
+        helpTestRewriteCriteria("((1=2) OR (1=2)) AND ((1=2) OR (1=2))", FALSE_STR); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteNot1() {
+        helpTestRewriteCriteria("NOT (1=1)", FALSE_STR);     //$NON-NLS-1$
+    }   
+
+    @Test public void testRewriteNot2() {
+        helpTestRewriteCriteria("NOT (1=2)", TRUE_STR);     //$NON-NLS-1$
+    }   
+    
+    @Test public void testRewriteNot3() {
+        helpTestRewriteCriteria("NOT (pm1.g1.e1='x')", "pm1.g1.e1 <> 'x'");     //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteDefect1() {
+        helpTestRewriteCriteria("(('DE' = 'LN') AND (null > '2002-01-01')) OR (('DE' = 'DE') AND (pm1.g1.e1 > '9000000'))", "(pm1.g1.e1 > '9000000')");         //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteQueryCriteriaAlwaysTrue() {
+        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE 0 = 0", //$NON-NLS-1$
+                                "SELECT e1 FROM pm1.g1"); //$NON-NLS-1$
+    }
+    
+    @Test public void testSubquery1() {
+        helpTestRewriteCommand("SELECT e1 FROM (SELECT e1 FROM pm1.g1 WHERE (1 - 1) = (0 + 0)) AS x", //$NON-NLS-1$
+                                "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x"); //$NON-NLS-1$
+    }
+
+    @Test public void testExistsSubquery() {
+        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+                                "SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
+    }
+
+    @Test public void testCompareSubqueryANY() {
+        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' = ANY (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+                                "SELECT e1 FROM pm1.g1 WHERE '3' = SOME (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
+    }
+
+    @Test public void testCompareSubquery() {
+        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' = SOME (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+                                "SELECT e1 FROM pm1.g1 WHERE '3' = SOME (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
+    }
+    
+    @Test public void testCompareSubqueryUnknown() {
+        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE null = SOME (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+                                "SELECT e1 FROM pm1.g1 WHERE null <> null"); //$NON-NLS-1$
+    }
+
+    @Test public void testINClauseSubquery() {
+        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+                                "SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteXMLCriteria1() {
+        helpTestRewriteCriteria("context(pm1.g1.e1, pm1.g1.e1) = convert(5, string)", "context(pm1.g1.e1, pm1.g1.e1) = '5'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteXMLCriteria2() {
+        helpTestRewriteCriteria("context(pm1.g1.e1, convert(5, string)) = 2+3", "context(pm1.g1.e1, '5') = '5'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    // HAS Criteria
+    @Test public void testRewriteProcedure1() throws Exception {
+    	
+		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
+		procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		
+		String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+		
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+		
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    // HAS Criteria
+    @Test public void testRewriteProcedure2() throws Exception {
+    	
+		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
+		procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n";		 //$NON-NLS-1$
+		procedure = procedure + "ELSE \n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n";		 //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		
+		String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    // HAS Criteria
+    @Test public void testRewriteProcedure3() throws Exception {
+    	
+		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
+		procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n";		 //$NON-NLS-1$
+		procedure = procedure + "ELSE \n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n";		 //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		
+		String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteProcedure4() throws Exception {
+    	
+		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
+		procedure = procedure + "IF (INPUT.e2 = 1)\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		
+		String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+		
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+		
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }    
+    
+    // CHANGING
+    @Test public void testRewriteProcedure5() throws Exception {
+    	
+		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
+		procedure = procedure + "IF (CHANGING.e1 = 'false')\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		
+		String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
+		
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+		
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    // CHANGING
+    @Test public void testRewriteProcedure6() throws Exception {
+    	
+		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
+		procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		
+		String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
+		
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+		
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }     
+    
+    // TRANSLATE CRITERIA
+    @Test public void testRewriteProcedure7() throws Exception {
+    	
+		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
+		procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		
+		String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
+		
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT e2 FROM pm1.g1 WHERE pm1.g1.e2 = 10;\n";				 //$NON-NLS-1$
+		rewritProc = rewritProc + "END";		 //$NON-NLS-1$
+		
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    // TRANSLATE CRITERIA
+    @Test public void testRewriteProcedure8() throws Exception {
+    	
+		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
+		procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g1.e2) with (vm1.g1.e2 = convert(sqrt(pm1.g1.e2), integer));\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		
+		String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
+		
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT e2 FROM pm1.g1 WHERE convert(sqrt(pm1.g1.e2), integer) = 10;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+		
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    // rewrite input/ changing variables
+    @Test public void testRewriteProcedure9() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "Declare String var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "if(var1 = 'x' or var1 = 'y')\n"; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n";         //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2, Input.e2, CHANGING.e2, CHANGING.e1 from pm1.g1 order by CHANGING.e1 + 1;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        String userQuery = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
+        
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE String var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "IF((var1 = 'x') OR (var1 = 'y'))\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT pm1.g1.e2, null, FALSE, TRUE FROM pm1.g1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.INSERT_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+    @Test public void testRewriteProcedure10() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2) WITH (e2 = pm1.g1.e2 + 20);\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 = e2 + 50"; //$NON-NLS-1$
+        
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e2 + 20) = ((pm1.g1.e2 + 20) + 50);\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+	// virtual group elements used in procedure in if statement(HAS CRITERIA)
+    @Test public void testRewriteProcedure11() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
+		procedure = procedure + "var1 = INPUT.e1;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g1 SET e1=40";     //$NON-NLS-1$
+        
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE string var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "var1 = '40';\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+	// with complex query transform
+    @Test public void testRewriteProcedure12() throws Exception {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (x = CONCAT(e1 , 'z'));\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where x =CONCAT(x , 'y')"; //$NON-NLS-1$
+        
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE CONCAT(e1, 'z') = CONCAT(CONCAT(e1, 'z'), 'y');\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+	// with complex query transform
+    @Test public void testRewriteProcedure13() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (x = CONCAT(e1 , 'z'), y = convert(CONCAT(e1 , 'k'), integer));\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where x =CONCAT(x , 'y') and y= 1"; //$NON-NLS-1$
+        
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE (CONCAT(e1, 'z') = CONCAT(CONCAT(e1, 'z'), 'y')) AND (convert(CONCAT(e1, 'k'), integer) = 1);\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+    @Test public void testRewriteProcedure14() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e4 = sqrt(e4));\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE sqrt(e4) = 1.0;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+	
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+    @Test public void testRewriteProcedure15() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e4 = e4/50);\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE e2 = 0;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+	
+	// virtual group elements used in procedure (TRANSLATE CRITERIA)
+    @Test public void testRewriteProcedure16() throws Exception {
+        String procedure = exampleTranslateUpdate();
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'x' WHERE e4 = 0.02;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+    
+    @Test public void testRewriteNoUserCriteria() throws Exception {
+        String procedure = exampleTranslateUpdate();
+
+        String userQuery = "UPDATE vm1.g3 SET x='x'"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'x' WHERE 1 = 1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+    
+    @Test public void testRewriteOrUserCriteria() throws Exception {
+        String procedure = exampleTranslateUpdate();
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where x = '1' or x = '2'"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'x' WHERE (CONCAT(e1, 'm') = '1') OR (CONCAT(e1, 'm') = '2');\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+
+	private String exampleTranslateUpdate() {
+		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "update pm1.g1 set pm1.g1.e1 = inputs.x where TRANSLATE CRITERIA;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+		return procedure;
+	}
+	
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+    @Test(expected=QueryValidatorException.class) public void testRewriteProcedure17() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE LIKE CRITERIA WITH (e4 = e4/50);\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
+
+		this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+	
+	// Bug 8212 elements in INPUT and CHANGING special groups are cese sensitive
+    @Test public void testRewriteProcedure18() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "Select Input.E1, Input.e2, CHANGING.e2, CHANGING.E1 from pm1.g1;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "INSERT into vm1.g1 (e1, E2) values('x', 1)"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT 'x', 1, TRUE, TRUE FROM pm1.g1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.INSERT_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+	
+	// elements being set in updates are dropped if INPUT var is not available, unless a default is available
+    // Note that this test is a little odd in that it is an update inside of an insert
+    @Test public void testRewriteProcedure19() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "update pm1.g1 set e1=Input.E1, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "INSERT into vm1.g1 (E2) values(1)"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'xyz', e2 = 1, e3 = TRUE;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.INSERT_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+	
+	// elements being set in updates are dropped if INPUT var is not available, unless a default is supplied
+    
+    //this test fails because the default for E1 'xyz' cannot be converted into a integer
+    @Test(expected=ExpressionEvaluationException.class) public void testRewriteProcedure21() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "INSERT into vm1.g1 (E3) values({b'true'})"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "UPDATE pm1.g1 SET e3 = TRUE;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		this.getRewritenProcedure(procedure, userQuery, FakeMetadataObject.Props.INSERT_PROCEDURE);
+	}
+    
+    @Test public void testRewriteProcedure21a() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "INSERT into vm1.g1 (E1) values(1)"; //$NON-NLS-1$
+
+        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = null, e2 = null, e3 = TRUE;\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+                                                        FakeMetadataObject.Props.INSERT_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+
+	// none of input variables on update statement changing
+    @Test public void testRewriteProcedure22() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "update vm1.g1 set E3 = {b'true'}"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+	
+	// none of input variables on update statement changing
+    @Test public void testRewriteProcedure23() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "update pm1.g1 set e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "update vm1.g1 set E1 = 'x'"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+    
+    //with an insert, defaults are used
+    @Test public void testRewriteProcedure23a() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "update pm1.g1 set e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "INSERT into vm1.g1 (E1) values('x')"; //$NON-NLS-1$
+
+        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "UPDATE pm1.g1 SET e2 = null, e3 = TRUE;\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+                FakeMetadataObject.Props.INSERT_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+	// elements being set in updates are dropped if INPUT var is not available
+    @Test(expected=QueryValidatorException.class) public void testRewriteProcedure24() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "UPDATE pm1.g1 SET e2=Input.e2 WHERE TRANSLATE LIKE CRITERIA ON (e1) WITH (e1=concat(pm1.g1.e1, '%'));\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g1 set E2=1 where e2 = 1 and e1 LIKE 'mnopxyz_'"; //$NON-NLS-1$
+
+		this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+
+	// INPUT vars in insert statements replaced by default variable when user's inser ignores values
+    @Test public void testRewriteProcedure25() throws Exception {
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "INSERT into pm1.g1 (e1,e2,e3,e4) values (Input.e1, Input.e2, Input.e3, Input.e4);"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "INSERT into vm1.g1 (E2) values (1)"; //$NON-NLS-1$
+
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES ('xyz', 1, TRUE, 123.456);\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.INSERT_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+	
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+	@Test public void testRewriteProcedure26() throws Exception {
+		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2);\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n";         //$NON-NLS-1$
+
+		String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 = e2 + 50"; //$NON-NLS-1$
+        
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e2 = (pm1.g1.e2 + 50);\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+		assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+	}
+	
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+	@Test(expected=QueryValidatorException.class) public void testRewriteProcedure27() throws Exception {
+		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+		procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2);\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n";         //$NON-NLS-1$
+
+		String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 LIKE 'xyz'"; //$NON-NLS-1$
+        
+		this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+
+    /**
+     * Per defect 9380 - 
+     * A criteria of the form  
+     * (? + 1) < (null)  
+     * caused a problem in the QueryRewriter.simplifyMathematicalCriteria method.
+     * At the beginning of the method, the null constant is rewritten so that it
+     * loses it's implicit type conversion to integer, then later on a function
+     * descriptor couldn't be found for the "minus" operation for the two types 
+     * integer and MetaMatrix's null type.
+     */
+    @Test public void testRewriteProcedure_9380() throws Exception {
+        
+        String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
+        procedure = procedure + "if((var1 + 1) < length(input.e1))\n"; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n";         //$NON-NLS-1$
+        procedure = procedure + "var2 = INPUT.e2;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g1 SET e2=30";     //$NON-NLS-1$
+        
+        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "BEGIN\n";         //$NON-NLS-1$
+        rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "DECLARE integer var2;\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    //base test.  no change is expected
+    @Test public void testRewriteLookupFunction1() {
+        String criteria = "lookup('pm1.g1','e1', 'e2', 1) = 'ab'"; //$NON-NLS-1$
+        CompareCriteria expected = (CompareCriteria)parseCriteria(criteria, FakeMetadataFactory.example1Cached()); 
+        helpTestRewriteCriteria(criteria, expected, FakeMetadataFactory.example1Cached());
+    }
+    
+    @Test public void testRewriteLookupFunction1b() {
+        helpTestRewriteCriteria("lookup('pm1.g1','e1', 'e2', pm1.g1.e2) = 'ab'", "lookup('pm1.g1','e1', 'e2', pm1.g1.e2) = 'ab'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** defect 11630 1 should still get rewritten as '1'*/
+    @Test public void testRewriteLookupFunctionCompoundCriteria() {
+        String criteria = "LOOKUP('pm1.g1','e1', 'e2', 1) IS NULL AND pm1.g1.e1='1'"; //$NON-NLS-1$
+        CompoundCriteria expected = (CompoundCriteria)parseCriteria(criteria, FakeMetadataFactory.example1Cached()); 
+        helpTestRewriteCriteria("LOOKUP('pm1.g1','e1', 'e2', 1) IS NULL AND pm1.g1.e1=1", expected, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+    }
+
+    @Test public void testSelectWithNoFrom() {
+        helpTestRewriteCommand("SELECT 5", "SELECT 5"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    //defect 9822
+    @Test public void testStoredProcedure_9822() throws Exception {
+
+        QueryParser parser = new QueryParser();
+        Command command = parser.parseCommand("exec pm1.sp4(5)");             //$NON-NLS-1$
+        
+        // resolve
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryResolver.resolveCommand(command, metadata);
+        
+        // rewrite
+        Command rewriteCommand = QueryRewriter.rewrite(command, metadata, null);
+        
+        List<SPParameter> parameters = ((StoredProcedure)rewriteCommand).getParameters();
+
+        for (SPParameter param : parameters) {
+            if(param.getParameterType() == ParameterInfo.IN || param.getParameterType() == ParameterInfo.INOUT){
+                assertTrue(param.getExpression() instanceof Constant);
+            }
+        }  
+    }
+    
+    @Test public void testRewriteFunctionThrowsEvaluationError() {
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        Criteria origCrit = parseCriteria("5 / 0 = 5", metadata); //$NON-NLS-1$
+        
+        // rewrite
+        try { 
+            QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
+            fail("Expected QueryValidatorException due to divide by 0"); //$NON-NLS-1$
+        } catch(TeiidException e) {
+        	// looks like message is being wrapped with another exception with same message
+            assertEquals("Error Code:ERR.015.001.0003 Message:Unable to evaluate (5 / 0): Error Code:ERR.015.001.0003 Message:Error while evaluating function /", e.getMessage());  //$NON-NLS-1$
+        }       
+    }
+    
+    @Test public void testRewriteConvertThrowsEvaluationError() {
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        Criteria origCrit = parseCriteria("convert('x', integer) = 0", metadata); //$NON-NLS-1$
+        
+        // rewrite
+        try { 
+            QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
+            fail("Expected QueryValidatorException due to invalid string"); //$NON-NLS-1$
+        } catch(TeiidException e) {
+            assertEquals("Error Code:ERR.015.001.0003 Message:Unable to evaluate convert('x', integer): Error Code:ERR.015.001.0003 Message:Error while evaluating function convert", e.getMessage()); //$NON-NLS-1$
+        }       
+    }
+    
+    @Test public void testDefect13458() throws Exception {
+    	
+		String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n";		 //$NON-NLS-1$
+		procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		procedure = procedure + "END\n"; //$NON-NLS-1$
+		
+		String userQuery = "delete from vm1.g1 where e1='1'"; //$NON-NLS-1$
+		
+		String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "BEGIN\n";		 //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "END"; //$NON-NLS-1$
+		
+		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.DELETE_PROCEDURE);				
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteCase1954() {
+        helpTestRewriteCriteria("convert(pm1.g1.e2, string) = '3'", "pm1.g1.e2 = 3"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCase1954a() {
+        helpTestRewriteCriteria("cast(pm1.g1.e2 as string) = '3'", "pm1.g1.e2 = 3"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCase1954b() throws Exception{
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+
+        CompareCriteria expected = new CompareCriteria();
+        ElementSymbol leftElement = new ElementSymbol("pm1.g1.e4"); //$NON-NLS-1$
+        Constant constant = new Constant(new Double(3.0), DataTypeManager.DefaultDataClasses.DOUBLE);
+        expected.setLeftExpression(leftElement);
+        expected.setRightExpression(constant);
+        // resolve against metadata
+        QueryResolver.resolveCriteria(expected, metadata);
+        
+        helpTestRewriteCriteria("convert(pm1.g1.e4, string) = '3.0'", expected, metadata); //$NON-NLS-1$ 
+    }    
+
+    @Test public void testRewriteCase1954c() {
+        helpTestRewriteCriteria("convert(pm1.g1.e1, string) = 'x'", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteCase1954d() {
+        helpTestRewriteCriteria("convert(pm1.g1.e1, timestamp) = {ts '2005-01-03 00:00:00.0'}", "pm1.g1.e1 = '2005-01-03 00:00:00.0'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCase1954e() {
+        helpTestRewriteCriteria("convert(pm1.g1.e4, integer) = 2", "convert(pm1.g1.e4, integer) = 2"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** Check that this fails, x is not convertable to an int */
+    @Test public void testRewriteCase1954f() {
+        helpTestRewriteCriteria("convert(pm1.g1.e2, string) = 'x'", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** Check that this returns true, x is not convertable to an int */
+    @Test public void testRewriteCase1954f1() {
+        helpTestRewriteCriteria("convert(pm1.g1.e2, string) != 'x'", "pm1.g1.e2 is not null"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCase1954Set() {
+        helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', '3')", "pm1.g1.e2 IN (2,3)"); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testRewriteCase1954SetA() {
+        helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', 'x')", "pm1.g1.e2 = 2"); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    @Test public void testRewriteCase1954SetB() {
+        helpTestRewriteCriteria("cast(pm1.g1.e2 as string) in ('2', '3')", "pm1.g1.e2 IN (2,3)"); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    @Test public void testRewriteCase1954SetC() {
+        helpTestRewriteCriteria("concat(pm1.g1.e2, 'string') in ('2', '3')", "concat(pm1.g1.e2, 'string') in ('2', '3')"); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testRewriteCase1954SetD() {
+        helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', pm1.g1.e1)", "convert(pm1.g1.e2, string) in ('2', pm1.g1.e1)"); //$NON-NLS-1$ //$NON-NLS-2$
+    }      
+    
+    // First WHEN always true, so rewrite as THEN expression
+    @Test public void testRewriteCaseExpr1() {
+        helpTestRewriteCriteria("case when 0=0 then 1 else 2 end = 1", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    // First WHEN always false, so rewrite as ELSE expression
+    @Test public void testRewriteCaseExpr2() {
+        helpTestRewriteCriteria("case when 0=1 then 1 else 2 end = 1", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    // First WHEN can't be rewritten, so no changes
+    @Test public void testRewriteCaseExpr3() {
+        helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then 1 else 2 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 1 ELSE 2 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCaseExpr4() {
+        helpTestRewriteCriteria("lookup('pm1.g1', 'e2', 'e1', case when 1=1 then pm1.g1.e1 end) = 0", "lookup('pm1.g1', 'e2', 'e1', pm1.g1.e1) = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    // First WHEN always false, so remove it
+    @Test public void testRewriteCaseExpr5() {
+        helpTestRewriteCriteria("case when 0=1 then 1 when 0 = pm1.g1.e2 then 2 else 3 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 2 ELSE 3 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCaseExprForCase5413aFrom502() {
+        helpTestRewriteCriteria("pm1.g2.e1 = case when 0 = pm1.g1.e2 then 2 else 2 end", "pm1.g2.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCaseExprForCase5413bFrom502() {
+        helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then null else null end IS NULL", TRUE_STR); //$NON-NLS-1$ 
+    }
+    
+    
+    @Test public void testRewriteCaseExprForCase5413a() {
+        helpTestRewriteCriteria("pm1.g2.e1 = case when 0 = pm1.g1.e2 then 2 else 2 end", "pm1.g2.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteCaseExprForCase5413b() {
+        helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then null else null end IS NULL", TRUE_STR); //$NON-NLS-1$ 
+    }
+
+    // First WHEN always true, so rewrite as THEN expression
+    @Test public void testRewriteSearchedCaseExpr1() {
+        helpTestRewriteCriteria("case 0 when 0 then 1 else 2 end = 1", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    // First WHEN always false, so rewrite as ELSE expression
+    @Test public void testRewriteSearchedCaseExpr2() {
+        helpTestRewriteCriteria("case 0 when 1 then 1 else 2 end = 1", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteSearchedCaseExpr3() {
+        helpTestRewriteCriteria("case 0 when pm1.g1.e2 then 1 else 2 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 1 ELSE 2 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteSearchedCaseExpr4() {
+        String criteria = "lookup('pm1.g1', 'e2', 'e1', '2') = 0"; //$NON-NLS-1$
+        CompareCriteria expected = (CompareCriteria)parseCriteria(criteria, FakeMetadataFactory.example1Cached()); 
+        helpTestRewriteCriteria("lookup('pm1.g1', 'e2', 'e1', case 0 when 1 then pm1.g1.e1 else 2 end) = 0", expected, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+    }
+
+    // First WHEN always false, so remove it
+    @Test public void testRewriteSearchedCaseExpr5() {
+        helpTestRewriteCriteria("case 0 when 1 then 1 when pm1.g1.e2 then 2 else 3 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 2 ELSE 3 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testDefect16879_1(){
+    	helpTestRewriteCommand("SELECT decodestring(e1, 'a, b') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testDefect16879_2(){
+    	helpTestRewriteCommand("SELECT decodestring(e1, 'a, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testDefect16879_3(){
+    	helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testDefect16879_4(){
+    	helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testDefect16879_5(){
+        helpTestRewriteCommand("SELECT decodeinteger(e1, 'null, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 IS NULL THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testDefect16879_6(){
+        helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, null, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 IS NULL THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testDefect16879_7(){
+        helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, null, d, e') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 IS NULL THEN 'd' ELSE 'e' END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testCaseExpressionThatResolvesToNull() {
+        String sqlBefore = "SELECT CASE 'x' WHEN 'Old Inventory System' THEN NULL WHEN 'New Inventory System' THEN NULL END"; //$NON-NLS-1$
+        String sqlAfter = "SELECT null"; //$NON-NLS-1$
+
+        Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
+        
+        ExpressionSymbol es = (ExpressionSymbol)cmd.getProjectedSymbols().get(0);
+        assertEquals( DataTypeManager.DefaultDataClasses.STRING, es.getType() );
+    }
+
+
+    //note that the env is now treated as deterministic, however it is really only deterministic within a session
+    @Test public void testRewriteExecEnv() throws Exception {
+        Command command = QueryParser.getQueryParser().parseCommand("exec pm1.sq2(env('sessionid'))");             //$NON-NLS-1$
+        
+        QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
+        
+        CommandContext context = new CommandContext();
+        Properties props = new Properties();
+        props.setProperty(ContextProperties.SESSION_ID, "1"); //$NON-NLS-1$
+        context.setEnvironmentProperties(props);
+        Command rewriteCommand = QueryRewriter.rewrite(command, FakeMetadataFactory.example1Cached(), context);
+        
+        assertEquals("EXEC pm1.sq2('1')", rewriteCommand.toString()); //$NON-NLS-1$
+    }
+
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteNestedFunctions() {
+        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 where convert(parsedate(e1, 'yyyy-MM-dd'), string) = '2006-07-01'", "SELECT e1 FROM pm1.g1 WHERE e1 = '2006-07-01'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Ignore(value="It's not generally possible to invert a narrowing conversion")
+    @Test public void testRewriteWithReference() {
+        helpTestRewriteCommand("SELECT e1 FROM pm1.g1 where parsetimestamp(e1, 'yyyy-MM-dd') != ?", "SELECT e1 FROM pm1.g1 WHERE e1 <> formattimestamp(?, 'yyyy-MM-dd')"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewiteJoinCriteria() {
+        helpTestRewriteCommand("SELECT pm1.g1.e1 FROM pm1.g1 inner join pm1.g2 on (pm1.g1.e1 = null)", "SELECT pm1.g1.e1 FROM pm1.g1 INNER JOIN pm1.g2 ON 1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewiteCompoundCriteria() {
+        helpTestRewriteCriteria("(pm1.g1.e1 = 1 and pm1.g1.e2 = 2) and (pm1.g1.e3 = 1 and pm1.g1.e4 = 2)", "(pm1.g1.e1 = '1') AND (pm1.g1.e2 = 2) AND (pm1.g1.e3 = TRUE) AND (pm1.g1.e4 = 2.0)"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteWhile() throws Exception {
+        
+        String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n";       //$NON-NLS-1$
+        procedure = procedure + "while (1 = 1)\n"; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "Select vm1.g1.e1 from vm1.g1;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+        
+        String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+        try {       
+            getRewritenProcedure(procedure, userQuery, FakeMetadataObject.Props.INSERT_PROCEDURE);
+            fail("exception expected"); //$NON-NLS-1$
+        } catch (QueryValidatorException e) {
+            assertEquals("Infinite loop detected, procedure will not be executed.", e.getMessage()); //$NON-NLS-1$
+        }
+    }
+    
+    @Test public void testRewriteWhile1() throws Exception {
+        
+        String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n";       //$NON-NLS-1$
+        procedure = procedure + "while (1 = 0)\n"; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "Select vm1.g1.e1 from vm1.g1;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+        
+        String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+        
+        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "BEGIN\n";         //$NON-NLS-1$
+        rewritProc = rewritProc + "END"; //$NON-NLS-1$
+        
+        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+                FakeMetadataObject.Props.INSERT_PROCEDURE);
+                
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    /**
+     * Tests that VariableSubstitutionVisitor does not cause an NPE on count(*)
+     */
+    @Test public void testRewriteProcedureWithCount() throws Exception {
+        
+        String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n";         //$NON-NLS-1$
+        procedure = procedure + "Select count(*) from pm1.g1;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+        
+        String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+        
+        String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "BEGIN\n";         //$NON-NLS-1$
+        rewritProc = rewritProc + "SELECT COUNT(*) FROM pm1.g1;\n";         //$NON-NLS-1$
+        rewritProc = rewritProc + "END"; //$NON-NLS-1$
+        
+        String procReturned = this.getRewritenProcedure(procedure, userQuery, 
+                FakeMetadataObject.Props.INSERT_PROCEDURE);
+                
+        assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+    }
+    
+    /**
+     * Test to ensure the update changing list retains e1 = ?
+     */
+    @Test public void testVariableSubstitutionVisitor() throws Exception {
+        String procedure1 = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure1 += "BEGIN\n"; //$NON-NLS-1$
+        procedure1 += "DECLARE string var1 = INPUT.e1;\n"; //$NON-NLS-1$
+        procedure1 += "ROWS_UPDATED = UPDATE vm1.g2 SET e1=var1;\n"; //$NON-NLS-1$
+        procedure1 += "END"; //$NON-NLS-1$
+        
+        String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
+        procedure2 += "BEGIN\n"; //$NON-NLS-1$
+        procedure2 += "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure2 += "IF (INPUT.e1 = 1)\n"; //$NON-NLS-1$
+        procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
+        procedure2 += "ELSE\n"; //$NON-NLS-1$
+        procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
+        procedure2 += "END"; //$NON-NLS-1$
+
+        String userUpdateStr = "UPDATE vm1.g1 SET e1 = 'x' WHERE e2 = 5"; //$NON-NLS-1$
+        
+        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure1, procedure2);
+        
+        String rewriten = getRewritenProcedure(userUpdateStr, metadata);
+        
+        String expected = "CREATE PROCEDURE\nBEGIN\nDECLARE string var1 = 'x';\nUPDATE vm1.g2 SET e1 = var1;\nROWS_UPDATED = VARIABLES.ROWCOUNT;\nEND"; //$NON-NLS-1$
+        
+        assertEquals(expected, rewriten);
+    }
+    
+    @Test public void testRemoveEmptyLoop() {
+        String procedure1 = "CREATE virtual PROCEDURE  "; //$NON-NLS-1$
+        procedure1 += "BEGIN\n"; //$NON-NLS-1$
+        procedure1 += "loop on (select e1 from pm1.g1) as myCursor\n"; //$NON-NLS-1$
+        procedure1 += "begin\n"; //$NON-NLS-1$
+        procedure1 += "end\n"; //$NON-NLS-1$
+        procedure1 += "select e1 from pm1.g1;\n"; //$NON-NLS-1$
+        procedure1 += "END"; //$NON-NLS-1$
+        
+        String expected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nSELECT e1 FROM pm1.g1;\nEND"; //$NON-NLS-1$
+        
+        helpTestRewriteCommand(procedure1, expected);
+    }
+    
+    @Test public void testRewriteDeclare() {
+        String procedure1 = "CREATE virtual PROCEDURE  "; //$NON-NLS-1$
+        procedure1 += "BEGIN\n"; //$NON-NLS-1$
+        procedure1 += "declare integer x = 1 + 1;\n"; //$NON-NLS-1$
+        procedure1 += "END"; //$NON-NLS-1$
+        
+        String expected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nDECLARE integer x = 2;\nEND"; //$NON-NLS-1$
+        
+        helpTestRewriteCommand(procedure1, expected);
+    }
+      
+    @Test public void testRewriteUnionJoin() {
+        String sql = "select pm1.g1.e1 from pm1.g1 union join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
+        String expected = "SELECT pm1.g1.e1 FROM pm1.g1 FULL OUTER JOIN pm1.g2 ON 1 = 0 WHERE g1.e1 = '1'"; //$NON-NLS-1$
+                
+        helpTestRewriteCommand(sql, expected);        
+    }
+
+    @Test public void testRewriteNonNullDependentFunction() {
+        helpTestRewriteCriteria("pm1.g1.e1 = concat(null, pm1.g1.e2)", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteInWithNull() {
+        helpTestRewriteCriteria("convert(null, string) in (pm1.g1.e1, pm1.g1.e2)", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteXMLCriteriaCases5630And5640() {
+        helpTestRewriteCommand("select * from xmltest.doc1 where node1 = null", "SELECT * FROM xmltest.doc1 WHERE null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCorrelatedSubqueryInHaving() {
+        String sql = "select pm1.g1.e1 from pm1.g1 group by pm1.g1.e1 having pm1.g1.e1 in (select pm1.g1.e1 from pm1.g2)"; //$NON-NLS-1$
+        String expected = "SELECT pm1.g1.e1 FROM pm1.g1 GROUP BY pm1.g1.e1 HAVING pm1.g1.e1 IN (SELECT pm1.g1.e1 FROM pm1.g2)"; //$NON-NLS-1$
+                
+        Query query = (Query)helpTestRewriteCommand(sql, expected);
+        
+        List<Reference> refs = new LinkedList<Reference>();
+        
+        CorrelatedReferenceCollectorVisitor.collectReferences(query, Arrays.asList(new GroupSymbol("pm1.g1")), refs);//$NON-NLS-1$
+        
+        assertEquals(1, refs.size());
+    }
+    
+    @Test public void testRewriteSelectInto() {
+        String sql = "select distinct pm1.g1.e1 into #temp from pm1.g1"; //$NON-NLS-1$
+        String expected = "INSERT INTO #temp (#TEMP.e1) SELECT DISTINCT pm1.g1.e1 FROM pm1.g1"; //$NON-NLS-1$
+                
+        helpTestRewriteCommand(sql, expected);        
+    }
+    
+    /**
+     * Accounts for type change with duplicate names
+     */
+    @Test public void testRewriteSelectInto1() {
+        String sql = "select distinct e2, e2, e3, e4 into pm1.g1 from pm1.g2"; //$NON-NLS-1$
+        String expected = "INSERT INTO pm1.g1 (pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4) SELECT PM1_G1_1.e2 AS e1, PM1_G1_1.E2_0 AS e2, PM1_G1_1.e3, PM1_G1_1.e4 FROM (SELECT DISTINCT e2, e2 AS E2_0, e3, e4 FROM pm1.g2) AS pm1_g1_1"; //$NON-NLS-1$
+                
+        helpTestRewriteCommand(sql, expected);        
+    }
+    
+    @Test public void testUnionQueryNullInOneBranch() throws Exception {
+        verifyProjectedTypesOnUnionBranches("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
+                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
+    }
+    
+    @Test public void testUnionQueryNullInOneBranch2() throws Exception {
+        verifyProjectedTypesOnUnionBranches("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e1, e2 FROM pm1.g2 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
+                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
+    }
+
+    @Test public void testUnionQueryNullInOneBranch3() throws Exception {
+        verifyProjectedTypesOnUnionBranches("SELECT e1, null FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g2", //$NON-NLS-1$
+                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
+    }
+
+    @Test public void testUnionQueryNullInAllBranches() throws Exception {
+        verifyProjectedTypesOnUnionBranches("SELECT e1, null FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
+                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
+    }
+    
+    @Test public void testUnionQueryWithTypeConversion() throws Exception {
+        verifyProjectedTypesOnUnionBranches("SELECT e1 FROM pm1.g1 UNION ALL SELECT e2 FROM pm1.g2", //$NON-NLS-1$
+                                            new Class[] { DataTypeManager.DefaultDataClasses.STRING});
+    }
+
+    private void verifyProjectedTypesOnUnionBranches(String unionQuery, Class<?>[] types) throws TeiidComponentException, TeiidProcessingException {
+        SetQuery union = (SetQuery)QueryParser.getQueryParser().parseCommand(unionQuery);
+        QueryResolver.resolveCommand(union, FakeMetadataFactory.example1Cached());
+        
+        union = (SetQuery)QueryRewriter.rewrite(union, FakeMetadataFactory.example1Cached(), null);
+        
+        for (QueryCommand query : union.getQueryCommands()) {
+            List<SingleElementSymbol> projSymbols = query.getProjectedSymbols();
+            for(int i=0; i<projSymbols.size(); i++) {
+                assertEquals("Found type mismatch at column " + i, types[i], projSymbols.get(i).getType()); //$NON-NLS-1$
+            }                
+        }
+    }
+        
+    /**
+     * The rewrite creates inline view to do the type conversion.
+     * 
+     * It also ensures that all project symbols are uniquely named in the inline view
+     */
+    @Test public void testSelectIntoWithOrderByAndTypeConversion() throws Exception {
+        String procedure = "CREATE VIRTUAL PROCEDURE\n"; //$NON-NLS-1$
+        procedure += "BEGIN\n";       //$NON-NLS-1$
+        procedure += "CREATE local temporary table temp (x string, y integer, z integer);\n";       //$NON-NLS-1$
+        procedure += "Select pm1.g1.e2, 1 as x, 2 as x into temp from pm1.g1 order by pm1.g1.e2 limit 1;\n"; //$NON-NLS-1$
+        procedure += "Select x from temp;\n"; //$NON-NLS-1$
+        procedure += "END\n"; //$NON-NLS-1$
+        
+        helpTestRewriteCommand(procedure, "CREATE VIRTUAL PROCEDURE\nBEGIN\nCREATE LOCAL TEMPORARY TABLE temp (x string, y integer, z integer);\nINSERT INTO temp (TEMP.x, TEMP.y, TEMP.z) SELECT TEMP_1.e2 AS x, TEMP_1.x AS y, TEMP_1.X_0 AS z FROM (SELECT pm1.g1.e2, 1 AS x, 2 AS X_0 FROM pm1.g1 ORDER BY pm1.g1.e2 LIMIT 1) AS temp_1;\nSELECT x FROM temp;\nEND"); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteNot() {
+        helpTestRewriteCriteria("not(not(pm1.g1.e1 = 1 + 1))", "pm1.g1.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteQueryWithNoFrom() {
+        String sql = "select 1 as a order by a"; //$NON-NLS-1$
+        
+        helpTestRewriteCommand(sql, "SELECT 1 AS a"); //$NON-NLS-1$
+    }
+        
+    /**
+     * Case 4814
+     */
+    @Test public void testVirtualRightOuterJoinSwap() throws Exception {
+        String sql = "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (select * from BQT1.smalla) sa RIGHT OUTER JOIN (select BQT1.mediumb.intkey from BQT1.mediumb) mb ON sa.IntKey = mb.IntKey"; //$NON-NLS-1$
+        helpTestRewriteCommand(sql, "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (SELECT BQT1.mediumb.intkey FROM BQT1.mediumb) AS mb LEFT OUTER JOIN (SELECT * FROM BQT1.smalla) AS sa ON sa.IntKey = mb.IntKey", FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+    }
+    
+    /**
+     * Case 4814
+     */
+    @Test public void testVirtualRightOuterJoinSwap1() throws Exception {
+        String sql = "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM ((select * from BQT1.smalla) sa inner join BQT1.smallb on sa.intkey = smallb.intkey) RIGHT OUTER JOIN (select BQT1.mediumb.intkey from BQT1.mediumb) mb ON sa.IntKey = mb.IntKey"; //$NON-NLS-1$
+        helpTestRewriteCommand(sql, "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (SELECT BQT1.mediumb.intkey FROM BQT1.mediumb) AS mb LEFT OUTER JOIN ((SELECT * FROM BQT1.smalla) AS sa INNER JOIN BQT1.smallb ON sa.intkey = smallb.intkey) ON sa.IntKey = mb.IntKey", FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteConcat2() {
+        helpTestRewriteCriteria("concat2('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteConcat2_1() {
+        helpTestRewriteCriteria("concat2(null, null) is null", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteConcat2_2() throws Exception {
+        helpTestRewriteCriteria("concat2(pm1.g1.e1, null) = 'xyz'", "CASE WHEN pm1.g1.e1 IS NULL THEN null ELSE concat(ifnull(pm1.g1.e1, ''), '') END = 'xyz'", true); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteConcat2_3() throws Exception {
+        helpTestRewriteCriteria("concat2(pm1.g1.e1, convert(pm1.g1.e2, string)) = 'xyz'", "CASE WHEN (pm1.g1.e1 IS NULL) AND (convert(pm1.g1.e2, string) IS NULL) THEN null ELSE concat(ifnull(pm1.g1.e1, ''), ifnull(convert(pm1.g1.e2, string), '')) END = 'xyz'", true); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteConcat2_4() throws Exception {
+        helpTestRewriteCriteria("concat2('a', pm1.g1.e1) = 'xyz'", "concat('a', ifnull(pm1.g1.e1, '')) = 'xyz'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewiteEvaluatableAggregate() {
+    	helpTestRewriteCommand("select pm1.g1.e1, max(1) from pm1.g1", "SELECT pm1.g1.e1, 1 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteFromUnixTime() throws Exception {
+    	TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$
+    	try {
+    		helpTestRewriteCriteria("from_unixtime(pm1.g1.e2) = '1992-12-01 07:00:00'", "timestampadd(SQL_TSI_SECOND, pm1.g1.e2, {ts'1969-12-31 18:00:00.0'}) = {ts'1992-12-01 07:00:00.0'}"); //$NON-NLS-1$ //$NON-NLS-2$
+    	} finally {
+    		TimestampWithTimezone.resetCalendar(null);
+    	}
+    }
+    
+    @Test public void testRewriteNullIf() throws Exception {
+    	helpTestRewriteCriteria("nullif(pm1.g1.e2, pm1.g1.e4) = 1", "CASE WHEN pm1.g1.e2 = pm1.g1.e4 THEN convert(null, double) ELSE pm1.g1.e2 END = 1.0", true); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteCoalesce() throws Exception {
+    	helpTestRewriteCriteria("coalesce(convert(pm1.g1.e2, double), pm1.g1.e4) = 1", "ifnull(convert(pm1.g1.e2, double), pm1.g1.e4) = 1", true); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /**
+     * Test <code>QueryRewriter</code>'s ability to rewrite a query that 
+     * contains an aggregate function which uses a <code>CASE</code> 
+     * expression which contains <code>BETWEEN</code> criteria as its value.
+     * <p>
+     * An aggregate function list is defined and queries are created that 
+     * use each function from the list.  The list includes:
+     * <p>
+     * "SUM", "MAX", "MIN", "AVG", "COUNT"   
+     * <p>
+     * It is expected that the BETWEEN expression will be rewritten as 
+     * <code>CompoundCriteria</code>.
+     * <p>
+     * <table>
+     * <tr><th align="left" colspan=2>For example:
+     * <tr><td width="10*"><td>SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 
+     * THEN e2 ELSE -1 END) FROM pm1.g1
+     * <tr><th align="left" colspan=2>Is rewritten as:
+     * <tr><td width="10*"><td>SELECT SUM(CASE WHEN (e2 >= 3) AND (e2 <= 5) 
+     * THEN e2 ELSE -1 END) FROM pm1.g1
+     * </table>
+     * 
+     * @see org.teiid.query.rewriter.QueryRewriter
+     * @see org.teiid.query.sql.lang.BetweenCriteria
+     * @see org.teiid.query.sql.lang.CompoundCriteria
+     * @see org.teiid.query.sql.symbol.AggregateSymbol
+     * @see org.teiid.query.sql.symbol.SearchedCaseExpression
+     */
+    @Test public void testAggregateWithBetweenInCaseInSelect() {
+    	// Define a list of aggregates to test against
+    	List<String> aggregateCommands = Arrays.asList( new String[] { "SUM", "MAX", "MIN", "AVG", "COUNT" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+    	
+    	// Define a query and the expected rewritten query
+    	// ?AGGREGATE? represents the string substitution for an aggregate from aggregateCommands
+    	String sqlBefore = "SELECT ?AGGREGATE?(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
+    	String sqlAfter  = "SELECT ?AGGREGATE?(CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
+
+    	// Iterate through the aggregateCommands
+    	for ( String aCmd : aggregateCommands ) {
+    		// Replace ?AGGREGATE? with the command from aggregateCommands
+    		String sql = sqlBefore.replace("?AGGREGATE?", aCmd); //$NON-NLS-1$
+    		String exSql = sqlAfter.replace("?AGGREGATE?", aCmd); //$NON-NLS-1$
+    		// Test QueryRewriter
+        	Command cmd = helpTestRewriteCommand( sql, exSql );
+        	// Check the rewritten command to verify that CompundCriteria replaced BetweenCriteria
+        	CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((ExpressionSymbol) cmd.getProjectedSymbols().get(0)).getExpression()).getWhen().get(0);
+        	assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
+        	assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
+    	}
+    }
+    
+    /**
+     * Test <code>QueryRewriter</code>'s ability to rewrite a query that 
+     * contains a <code>CASE</code> expression which contains 
+     * <code>BETWEEN</code> criteria in the queries <code>SELECT</code> clause.
+     * <p>
+     * It is expected that the BETWEEN expression will be rewritten as 
+     * <code>CompoundCriteria</code>.
+     * <p>
+     * <table>
+     * <tr><th align="left" colspan=2>For example:
+     * <tr><td width="10*"><td>SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 
+     * ELSE -1 END FROM pm1.g1 
+     * <tr><th align="left" colspan=2>Is rewritten as:
+     * <tr><td width="10*"><td>SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 
+     * ELSE -1 END FROM pm1.g1
+     * </table>
+     * 
+     * @see org.teiid.query.rewriter.QueryRewriter
+     * @see org.teiid.query.sql.lang.BetweenCriteria
+     * @see org.teiid.query.sql.lang.CompoundCriteria
+     * @see org.teiid.query.sql.symbol.SearchedCaseExpression
+     */
+    @Test public void testBetweenInCaseInSelect() {
+    	String sqlBefore = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
+    	String sqlAfter = "SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
+    	
+    	Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
+    	CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((ExpressionSymbol) cmd.getProjectedSymbols().get(0)).getExpression()).getWhen().get(0);
+    	assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
+    	assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
+    }
+    
+    /**
+     * Test <code>QueryRewriter</code>'s ability to rewrite a query that 
+     * contains a <code>CASE</code> expression which contains 
+     * <code>BETWEEN</code> criteria in the queries <code>WHERE</code> clause.
+     * <p>
+     * It is expected that the BETWEEN expression will be rewritten as 
+     * <code>CompoundCriteria</code>.
+     * <p>
+     * <table>
+     * <tr><th align="left" colspan=2>For example:
+     * <tr><td width="10*"><td>SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 
+     * BETWEEN 3 AND 5 THEN e2 ELSE -1 END 
+     * <tr><th align="left" colspan=2>Is rewritten as:
+     * <tr><td width="10*"><td>SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN  
+     * (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END
+     * </table>
+     * 
+     * @see org.teiid.query.rewriter.QueryRewriter
+     * @see org.teiid.query.sql.lang.BetweenCriteria
+     * @see org.teiid.query.sql.lang.CompoundCriteria
+     * @see org.teiid.query.sql.symbol.SearchedCaseExpression
+     */
+    @Test public void testBetweenInCase() {
+    	String sqlBefore = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END"; //$NON-NLS-1$
+    	String sqlAfter = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END"; //$NON-NLS-1$
+    	
+    	Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
+    	CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((CompareCriteria) ((Query) cmd).getCriteria()).getRightExpression()).getWhen().get(0);
+    	assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
+    	assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteNullHandling() {
+    	String original = "pm1.g1.e1 like '%'"; //$NON-NLS-1$
+    	String expected = "pm1.g1.e1 is not null"; //$NON-NLS-1$
+    	
+    	helpTestRewriteCriteria(original, expected);
+    }
+    
+    @Test public void testRewriteNullHandling1() {
+    	String original = "not(pm1.g1.e1 like '%' or pm1.g1.e1 = '1')"; //$NON-NLS-1$
+    	String expected = "1 = 0"; //$NON-NLS-1$
+    	
+    	helpTestRewriteCriteria(original, expected);
+    }
+    
+    @Test public void testRewriteNullHandling2() {
+    	String original = "not(pm1.g1.e1 like '%' and pm1.g1.e1 = '1')"; //$NON-NLS-1$
+    	String expected = "pm1.g1.e1 <> '1'"; //$NON-NLS-1$
+    	
+    	helpTestRewriteCriteria(original, expected);
+    }
+    
+    @Test public void testRewriteNullHandling3() {
+    	String original = "pm1.g1.e1 like '%' or pm1.g1.e1 = '1'"; //$NON-NLS-1$
+    	String expected = "(pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e1 = '1')"; //$NON-NLS-1$
+    	
+    	helpTestRewriteCriteria(original, expected);
+    }
+    
+    @Test public void testRewriteNullHandling4() {
+    	String original = "not((pm1.g1.e1 like '%' or pm1.g1.e1 = '1') and pm1.g1.e2 < 5)"; //$NON-NLS-1$
+    	String expected = "(pm1.g1.e2 < 5) AND ((pm1.g1.e2 < 5) OR (pm1.g1.e1 <> '1'))"; //$NON-NLS-1$
+    	
+    	helpTestRewriteCriteria(original, expected);
+    }
+    
+    @Test public void testRewriteNullHandling5() {
+    	String original = "not(pm1.g1.e1 not like '%' and pm1.g1.e3 = '1') or pm1.g1.e2 < 5"; //$NON-NLS-1$
+    	String expected = "(pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e3 <> TRUE) OR (pm1.g1.e2 < 5)"; //$NON-NLS-1$
+    	
+    	helpTestRewriteCriteria(original, expected);
+    }
+    
+    @Test public void testRewriteChar() {
+    	String original = "convert(pm1.g1.e1, char) = '100'"; //$NON-NLS-1$
+    	String expected = "1 = 0"; //$NON-NLS-1$
+    	
+    	helpTestRewriteCriteria(original, expected);
+    }
+    
+    /**
+     * Test ensures that '22.0' is a valid long via bigdecimal
+     */
+    @Test public void testRewriteBigDecimal() {
+    	String original = "convert(BQT1.SmallA.LongNum, bigdecimal) = '22.0'"; //$NON-NLS-1$
+    	CompareCriteria crit = new CompareCriteria(new ElementSymbol("BQT1.SmallA.LongNum"), CompareCriteria.EQ, new Constant(new Long(22))); //$NON-NLS-1$
+    	helpTestRewriteCriteria(original, crit, FakeMetadataFactory.exampleBQTCached()); 
+    }
+
+    /**
+     * Test ensures that we will not attempt to invert the widening conversion
+     */
+    @Test public void testRewriteWideningIn() {
+    	String original = "convert(BQT1.SmallA.TimestampValue, time) in ({t'10:00:00'}, {t'11:00:00'})"; //$NON-NLS-1$
+    	helpTestRewriteCriteria(original, parseCriteria("convert(BQT1.SmallA.TimestampValue, time) in ({t'10:00:00'}, {t'11:00:00'})", FakeMetadataFactory.exampleBQTCached()), FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testRewriteParseDate() {
+    	String original = "parsedate(BQT1.SmallA.stringkey, 'yymmdd') = {d'1970-01-01'}"; //$NON-NLS-1$
+    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	helpTestRewriteCriteria(original, parseCriteria("convert(parsetimestamp(BQT1.SmallA.stringkey, 'yymmdd'), date) = {d'1970-01-01'}", metadata), metadata); //$NON-NLS-1$
+    }
+
+    @Test public void testRewriteFormatTime() {
+    	String original = "formattime(BQT1.SmallA.timevalue, 'hh:mm') = '08:02'"; //$NON-NLS-1$
+    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	helpTestRewriteCriteria(original, parseCriteria("formattimestamp(convert(BQT1.SmallA.timevalue, timestamp), 'hh:mm') = '08:02'", metadata), metadata); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteTimestampAdd() {
+    	String original = "timestampadd(SQL_TSI_SECOND, 1, BQT1.SmallA.timevalue) = {t'08:02:00'}"; //$NON-NLS-1$
+    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	helpTestRewriteCriteria(original, parseCriteria("convert(timestampadd(SQL_TSI_SECOND, 1, convert(BQT1.SmallA.timevalue, timestamp)), time) = {t'08:02:00'}", metadata), metadata); //$NON-NLS-1$
+    }
+    
+    @Test public void testRewriteXmlElement() throws Exception {
+    	String original = "xmlserialize(document xmlelement(name a, xmlattributes('b' as c)) as string)"; //$NON-NLS-1$
+    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	helpTestRewriteExpression(original, "'<a c=\"b\"></a>'", metadata);
+    }
+    
+    @Test public void testRewriteXmlElement1() throws Exception {
+    	String original = "xmlelement(name a, xmlattributes(1+1 as c), BQT1.SmallA.timevalue)"; //$NON-NLS-1$
+    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	helpTestRewriteExpression(original, "XMLELEMENT(NAME a, XMLATTRIBUTES(2 AS c), BQT1.SmallA.timevalue)", metadata);
+    }
+    
+    @Test public void testRewriteXmlSerialize() throws Exception {
+    	String original = "xmlserialize(document xmlelement(name a, xmlattributes('b' as c)) as string)"; //$NON-NLS-1$
+    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	helpTestRewriteExpression(original, "'<a c=\"b\"></a>'", metadata);
+    }
+    
+    @Test public void testRewriteXmlTable() throws Exception {
+    	String original = "select * from xmltable('/' passing 1 + 1 as a columns x string default curdate()) as x"; //$NON-NLS-1$
+    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	helpTestRewriteCommand(original, "SELECT * FROM XMLTABLE('/' PASSING 2 AS a COLUMNS x string DEFAULT curdate()) AS x", metadata);
+    }
+    
+    @Test public void testRewriteQueryString() throws Exception {
+    	String original = "querystring('path', 'value' as \"&x\", ' & ' as y, null as z)"; //$NON-NLS-1$
+    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	helpTestRewriteExpression(original, "'path?%26x=value&y=%20%26%20'", metadata);
+    }
+    
+    @Test public void testRewriteExpressionCriteria() throws Exception {
+    	helpTestRewriteCriteria("pm1.g1.e3", "pm1.g1.e3 = true");
+    }
+
+}

Deleted: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
===================================================================
--- branches/7.2.x/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,616 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.unittest;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.ColumnSet;
-import org.teiid.metadata.KeyRecord;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Procedure;
-import org.teiid.metadata.ProcedureParameter;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-import org.teiid.metadata.BaseColumn.NullType;
-import org.teiid.metadata.Column.SearchType;
-import org.teiid.metadata.ProcedureParameter.Type;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.metadata.CompositeMetadataStore;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.sql.lang.SPParameter;
-
- at SuppressWarnings("nls")
-public class RealMetadataFactory {
-
-    private static TransformationMetadata CACHED_BQT = exampleBQT();
-        
-	private RealMetadataFactory() { }
-	
-    public static TransformationMetadata exampleBQTCached() {
-        return CACHED_BQT;
-    }
-    
-    public static TransformationMetadata exampleBQT() {
-    	MetadataStore metadataStore = new MetadataStore();
-    	
-        Schema bqt1 = createPhysicalModel("BQT1", metadataStore); //$NON-NLS-1$
-        Schema bqt2 = createPhysicalModel("BQT2", metadataStore); //$NON-NLS-1$
-        Schema bqt3 = createPhysicalModel("BQT3", metadataStore); //$NON-NLS-1$
-        Schema lob = createPhysicalModel("LOB", metadataStore); //$NON-NLS-1$
-        Schema vqt = createVirtualModel("VQT", metadataStore); //$NON-NLS-1$
-        Schema bvqt = createVirtualModel("BQT_V", metadataStore); //$NON-NLS-1$
-        Schema bvqt2 = createVirtualModel("BQT2_V", metadataStore); //$NON-NLS-1$
-        
-        // Create physical groups
-        Table bqt1SmallA = createPhysicalGroup("SmallA", bqt1); //$NON-NLS-1$
-        Table bqt1SmallB = createPhysicalGroup("SmallB", bqt1); //$NON-NLS-1$
-        Table bqt1MediumA = createPhysicalGroup("MediumA", bqt1); //$NON-NLS-1$
-        Table bqt1MediumB = createPhysicalGroup("MediumB", bqt1); //$NON-NLS-1$
-        Table bqt2SmallA = createPhysicalGroup("SmallA", bqt2); //$NON-NLS-1$
-        Table bqt2SmallB = createPhysicalGroup("SmallB", bqt2); //$NON-NLS-1$
-        Table bqt2MediumA = createPhysicalGroup("MediumA", bqt2); //$NON-NLS-1$
-        Table bqt2MediumB = createPhysicalGroup("MediumB", bqt2); //$NON-NLS-1$
-        Table bqt3SmallA = createPhysicalGroup("SmallA", bqt3); //$NON-NLS-1$
-        Table bqt3SmallB = createPhysicalGroup("SmallB", bqt3); //$NON-NLS-1$
-        Table bqt3MediumA = createPhysicalGroup("MediumA", bqt3); //$NON-NLS-1$
-        Table bqt3MediumB = createPhysicalGroup("MediumB", bqt3); //$NON-NLS-1$
-        Table lobTable = createPhysicalGroup("LobTbl", lob); //$NON-NLS-1$
-        Table library = createPhysicalGroup("LOB_TESTING_ONE", lob); //$NON-NLS-1$
-        
-        createElements( library, new String[] { "CLOB_COLUMN", "BLOB_COLUMN", "KEY_EMULATOR" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        		new String[] { DataTypeManager.DefaultDataTypes.CLOB, DataTypeManager.DefaultDataTypes.BLOB, DataTypeManager.DefaultDataTypes.INTEGER }); 
-
-        // Create virtual groups
-        QueryNode vqtn1 = new QueryNode("VQT.SmallA", "SELECT * FROM BQT1.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg1 = createUpdatableVirtualGroup("SmallA", vqt, vqtn1); //$NON-NLS-1$
-        
-        QueryNode vqtn2 = new QueryNode("VQT.SmallB", "SELECT Concat(stringKey, stringNum) as a12345 FROM BQT1.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2 = createUpdatableVirtualGroup("SmallB", vqt, vqtn2); //$NON-NLS-1$        
-
-        // Case 2589
-        QueryNode vqtn2589 = new QueryNode("VQT.SmallA_2589", "SELECT * FROM BQT1.SmallA WHERE StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2589 = createVirtualGroup("SmallA_2589", vqt, vqtn2589); //$NON-NLS-1$
-
-        QueryNode vqtn2589a = new QueryNode("VQT.SmallA_2589a", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.IntKey = SmallB.IntKey WHERE SmallA.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2589a = createVirtualGroup("SmallA_2589a", vqt, vqtn2589a); //$NON-NLS-1$
-
-        QueryNode vqtn2589b = new QueryNode("VQT.SmallA_2589b", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2589b = createVirtualGroup("SmallA_2589b", vqt, vqtn2589b); //$NON-NLS-1$
-
-        QueryNode vqtn2589c = new QueryNode("VQT.SmallA_2589c", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE concat(SmallA.StringNum, SmallB.StringNum) = '1010'"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2589c = createVirtualGroup("SmallA_2589c", vqt, vqtn2589c); //$NON-NLS-1$
-        
-        QueryNode vqtn2589d = new QueryNode("VQT.SmallA_2589d", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10' AND SmallA.IntNum = 10"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2589d = createVirtualGroup("SmallA_2589d", vqt, vqtn2589d); //$NON-NLS-1$
-
-        QueryNode vqtn2589f = new QueryNode("VQT.SmallA_2589f", "SELECT * FROM VQT.SmallA_2589"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2589f = createVirtualGroup("SmallA_2589f", vqt, vqtn2589f); //$NON-NLS-1$
-
-        QueryNode vqtn2589g = new QueryNode("VQT.SmallA_2589g", "SELECT * FROM VQT.SmallA_2589b"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2589g = createVirtualGroup("SmallA_2589g", vqt, vqtn2589g); //$NON-NLS-1$
-
-        QueryNode vqtn2589h = new QueryNode("VQT.SmallA_2589h", "SELECT VQT.SmallA_2589.* FROM VQT.SmallA_2589 INNER JOIN BQT1.SmallB ON VQT.SmallA_2589.StringKey = SmallB.StringKey"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2589h = createVirtualGroup("SmallA_2589h", vqt, vqtn2589h); //$NON-NLS-1$
-        
-        QueryNode vqtn2589i = new QueryNode("VQT.SmallA_2589i", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10' AND SmallB.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg2589i = createVirtualGroup("SmallA_2589i", vqt, vqtn2589i); //$NON-NLS-1$
-
-        // defect 15355
-        QueryNode vqtn15355  = new QueryNode("VQT.Defect15355", "SELECT convert(IntKey, string) as StringKey, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg15355  = createVirtualGroup("Defect15355", vqt, vqtn15355); //$NON-NLS-1$
-        QueryNode vqtn15355a  = new QueryNode("VQT.Defect15355a", "SELECT StringKey, StringNum, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, StringNum, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg15355a  = createVirtualGroup("Defect15355a", vqt, vqtn15355a); //$NON-NLS-1$
-        QueryNode vqtn15355b  = new QueryNode("VQT.Defect15355b", "SELECT convert(IntKey, string) as IntKey, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table vqtg15355b  = createVirtualGroup("Defect15355b", vqt, vqtn15355b); //$NON-NLS-1$
-        
-        QueryNode bvqtn1 = new QueryNode("BQT_V.BQT_V", "SELECT a.* FROM BQT1.SMALLA AS a WHERE a.INTNUM = (SELECT MIN(b.INTNUM) FROM BQT1.SMALLA AS b WHERE b.INTKEY = a.IntKey ) OPTION MAKEDEP a"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table bvqtg1 = createUpdatableVirtualGroup("BQT_V", bvqt, bvqtn1); //$NON-NLS-1$
-        QueryNode bvqt2n1 = new QueryNode("BQT2_V.BQT2_V", "SELECT BQT2.SmallA.* FROM BQT2.SmallA, BQT_V.BQT_V WHERE BQT2.SmallA.IntKey = BQT_V.BQT_V.IntKey"); //$NON-NLS-1$ //$NON-NLS-2$
-        Table bvqt2g1 = createUpdatableVirtualGroup("BQT2_V", bvqt2, bvqt2n1); //$NON-NLS-1$
-
-     // Create physical elements
-        String[] elemNames = new String[] { 
-             "IntKey", "StringKey",  //$NON-NLS-1$ //$NON-NLS-2$
-             "IntNum", "StringNum",  //$NON-NLS-1$ //$NON-NLS-2$
-             "FloatNum", "LongNum",  //$NON-NLS-1$ //$NON-NLS-2$
-             "DoubleNum", "ByteNum",  //$NON-NLS-1$ //$NON-NLS-2$
-             "DateValue", "TimeValue",  //$NON-NLS-1$ //$NON-NLS-2$
-             "TimestampValue", "BooleanValue",  //$NON-NLS-1$ //$NON-NLS-2$
-             "CharValue", "ShortValue",  //$NON-NLS-1$ //$NON-NLS-2$
-             "BigIntegerValue", "BigDecimalValue",  //$NON-NLS-1$ //$NON-NLS-2$
-             "ObjectValue" }; //$NON-NLS-1$
-         String[] elemTypes = new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, 
-                             DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, 
-                             DataTypeManager.DefaultDataTypes.FLOAT, DataTypeManager.DefaultDataTypes.LONG, 
-                             DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.BYTE, 
-                             DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, 
-                             DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.DefaultDataTypes.BOOLEAN, 
-                             DataTypeManager.DefaultDataTypes.CHAR, DataTypeManager.DefaultDataTypes.SHORT, 
-                             DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL, 
-                             DataTypeManager.DefaultDataTypes.OBJECT };
-        
-        List<Column> bqt1SmallAe = createElements(bqt1SmallA, elemNames, elemTypes);
-        bqt1SmallAe.get(1).setNativeType("char"); //$NON-NLS-1$
-        createElements(bqt1SmallB, elemNames, elemTypes);
-        createElements(bqt1MediumA, elemNames, elemTypes);
-        createElements(bqt1MediumB, elemNames, elemTypes);
-        createElements(bqt2SmallA, elemNames, elemTypes);
-        createElements(bqt2SmallB, elemNames, elemTypes);
-        createElements(bqt2MediumA, elemNames, elemTypes);
-        createElements(bqt2MediumB, elemNames, elemTypes);                
-        createElements(bqt3SmallA, elemNames, elemTypes);
-        createElements(bqt3SmallB, elemNames, elemTypes);
-        createElements(bqt3MediumA, elemNames, elemTypes);
-        createElements(bqt3MediumB, elemNames, elemTypes);
-        createElements(lobTable, new String[] {"ClobValue"}, new String[] {DataTypeManager.DefaultDataTypes.CLOB}); //$NON-NLS-1$
-        
-        // Create virtual elements
-        createElements(vqtg1, elemNames, elemTypes);        
-        createElements(vqtg2, new String[] {"a12345"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});  //$NON-NLS-1$
-        createElements(vqtg15355, new String[] {"StringKey", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER});         //$NON-NLS-1$ //$NON-NLS-2$
-        createElements(vqtg15355a, new String[] {"StringKey", "StringNum", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER});         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        createElements(vqtg15355b, new String[] {"IntKey", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER});         //$NON-NLS-1$ //$NON-NLS-2$
-        createElements(vqtg2589, elemNames, elemTypes);        
-        createElements(vqtg2589a, elemNames, elemTypes);        
-        createElements(vqtg2589b, elemNames, elemTypes);        
-        createElements(vqtg2589c, elemNames, elemTypes);        
-        createElements(vqtg2589d, elemNames, elemTypes);        
-        createElements(vqtg2589f, elemNames, elemTypes);        
-        createElements(vqtg2589g, elemNames, elemTypes);        
-        createElements(vqtg2589h, elemNames, elemTypes);        
-        createElements(vqtg2589i, elemNames, elemTypes);
-        createElements(bvqtg1, elemNames, elemTypes);        
-        createElements(bvqt2g1, elemNames, elemTypes);        
-
-     // Add stored procedure
-        Schema pm1 = createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
-        ProcedureParameter rs1p1 = createParameter("intkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);         //$NON-NLS-1$
-        ColumnSet<Procedure> rs1 = createResultSet("rs1", new String[] { "IntKey", "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        Procedure spTest5 = createStoredProcedure("spTest5", pm1, Arrays.asList(rs1p1), "spTest5"); //$NON-NLS-1$ //$NON-NLS-2$
-        spTest5.setResultSet(rs1);
-
-        Schema pm2 = createPhysicalModel("pm2", metadataStore); //$NON-NLS-1$
-        ProcedureParameter rs2p1 = createParameter("inkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
-        ProcedureParameter rs2p2 = createParameter("outkey", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER);                 //$NON-NLS-1$
-        ColumnSet<Procedure> rs2 = createResultSet("rs2", new String[] { "IntKey", "StringKey"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        Procedure spTest8 = createStoredProcedure("spTest8", pm2, Arrays.asList(rs2p1, rs2p2), "spTest8"); //$NON-NLS-1$ //$NON-NLS-2$
-        spTest8.setResultSet(rs2);
-        
-        ProcedureParameter rs2p2a = createParameter("outkey", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER);                 //$NON-NLS-1$
-        ColumnSet<Procedure> rs2a = createResultSet("rs2", new String[] { "IntKey", "StringKey"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        Procedure spTest8a = createStoredProcedure("spTest8a", pm2, Arrays.asList(rs2p2a), "spTest8a"); //$NON-NLS-1$ //$NON-NLS-2$
-        spTest8a.setResultSet(rs2a);
-        
-        Schema pm4 = createPhysicalModel("pm4", metadataStore); //$NON-NLS-1$
-        ProcedureParameter rs4p1 = createParameter("ret", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
-        ProcedureParameter rs4p2 = createParameter("inkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
-        createStoredProcedure("spTest9", pm4, Arrays.asList(rs4p1, rs4p2), "spTest9"); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        Schema pm3 = createPhysicalModel("pm3", metadataStore); //$NON-NLS-1$
-        ProcedureParameter rs3p1 = createParameter("inkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
-        ProcedureParameter rs3p2 = createParameter("outkey", ParameterInfo.INOUT, DataTypeManager.DefaultDataTypes.INTEGER);                 //$NON-NLS-1$
-        ColumnSet<Procedure> rs3 = createResultSet("rs3", new String[] { "IntKey", "StringKey"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        Procedure spTest11 = createStoredProcedure("spTest11", pm3, Arrays.asList(rs3p1, rs3p2), "spTest11"); //$NON-NLS-1$ //$NON-NLS-2$
-        spTest11.setResultSet(rs3);
-        
-        //add virtual stored procedures 
-        Schema mmspTest1 = createVirtualModel("mmspTest1", metadataStore); //$NON-NLS-1$
-        ColumnSet<Procedure> vsprs1 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        QueryNode vspqn1 = new QueryNode("vsp1", "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor BEGIN x= intKeyCursor.intkey - 1; END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        Procedure vsp1 = createVirtualProcedure("MMSP1", mmspTest1, null, vspqn1); //$NON-NLS-1$
-        vsp1.setResultSet(vsprs1);
-
-        ColumnSet<Procedure> vsprs2 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        QueryNode vspqn2 = new QueryNode("vsp2", "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor1 BEGIN LOOP ON (SELECT intkey FROM bqt1.smallB) AS intKeyCursor2 BEGIN x= intKeyCursor1.intkey - intKeyCursor2.intkey; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        Procedure vsp2 = createVirtualProcedure("MMSP2", mmspTest1, null, vspqn2); //$NON-NLS-1$
-        vsp2.setResultSet(vsprs2);
-
-        ColumnSet<Procedure> vsprs3 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        QueryNode vspqn3 = new QueryNode("vsp3", "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor BEGIN x= intKeyCursor.intkey - 1; if(x = 25) BEGIN BREAK; END ELSE BEGIN CONTINUE; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        Procedure vsp3 = createVirtualProcedure("MMSP3", mmspTest1, null, vspqn3); //$NON-NLS-1$
-        vsp3.setResultSet(vsprs3);
-
-        ColumnSet<Procedure> vsprs4 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        QueryNode vspqn4 = new QueryNode("vsp4", "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE(x < 50) BEGIN x= x + 1; if(x = 25) BEGIN BREAK; END ELSE BEGIN CONTINUE; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        Procedure vsp4 = createVirtualProcedure("MMSP4", mmspTest1, null, vspqn4); //$NON-NLS-1$
-        vsp4.setResultSet(vsprs4);
-        
-        ColumnSet<Procedure> vsprs5 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        ProcedureParameter vsp5p1 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
-        QueryNode vspqn5 = new QueryNode("vsp5", "CREATE VIRTUAL PROCEDURE BEGIN SELECT 0; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        Procedure vsp5 = createVirtualProcedure("MMSP5", mmspTest1, Arrays.asList(vsp5p1), vspqn5); //$NON-NLS-1$
-        vsp5.setResultSet(vsprs5);
-
-        ColumnSet<Procedure> vsprs6 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        ProcedureParameter vsp6p1 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
-        QueryNode vspqn6 = new QueryNode("vsp6", "CREATE VIRTUAL PROCEDURE BEGIN SELECT p1 as StringKey; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        Procedure vsp6 = createVirtualProcedure("MMSP6", mmspTest1, Arrays.asList(vsp6p1), vspqn6); //$NON-NLS-1$
-        vsp6.setResultSet(vsprs6);
-        
-        createStoredProcedure("spRetOut", pm4, Arrays.asList(createParameter("ret", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER),
-        		createParameter("x", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER)), "spRetOut"); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        ColumnSet<Procedure> vsprs7 = createResultSet("TEIIDSP7.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        ProcedureParameter vsp7p1 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
-        QueryNode vspqn7 = new QueryNode("TEIIDSP7", "CREATE VIRTUAL PROCEDURE BEGIN declare integer x; x = exec spTest9(p1); declare integer y; exec spTest11(inkey=>x, outkey=>y); select convert(x, string) || y; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        Procedure vsp7 = createVirtualProcedure("TEIIDSP7", mmspTest1, Arrays.asList(vsp7p1), vspqn7); //$NON-NLS-1$
-        vsp7.setResultSet(vsprs7);
-        
-    	return createTransformationMetadata(metadataStore, "bqt"); 
-    }
-
-	public static TransformationMetadata createTransformationMetadata(
-			MetadataStore metadataStore, String vdbName) {
-		CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
-    	VDBMetaData vdbMetaData = new VDBMetaData();
-    	vdbMetaData.setName(vdbName); //$NON-NLS-1$
-    	vdbMetaData.setVersion(1);
-    	for (Schema schema : metadataStore.getSchemas().values()) {
-			vdbMetaData.addModel(FakeMetadataFactory.createModel(schema.getName(), schema.isPhysical()));
-		}
-    	return new TransformationMetadata(vdbMetaData, store, null, null, FakeMetadataFactory.SFM.getSystemFunctions());
-	}
-    
-    /** 
-     * Metadata for Materialized Views
-     * @return
-     * @since 4.2
-     */
-    public static QueryMetadataInterface exampleMaterializedView() {
-    	MetadataStore metadataStore = new MetadataStore();
-        Schema virtModel = createVirtualModel("MatView", metadataStore); //$NON-NLS-1$
-        Schema physModel = createPhysicalModel("MatTable", metadataStore); //$NON-NLS-1$
-        Schema physModel_virtSrc = createPhysicalModel("MatSrc", metadataStore); //$NON-NLS-1$
-        
-        Table physTable = createPhysicalGroup("info", physModel); //$NON-NLS-1$
-        createElements(physTable,
-                                      new String[] { "e1", "e2", "e3"}, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-        
-        Table physGroup = createPhysicalGroup("MatTable", physModel); //$NON-NLS-1$
-        createElements(physGroup,
-                                      new String[] { "e1" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        
-        Table physGroupStage = createPhysicalGroup("MatStage", physModel); //$NON-NLS-1$
-        createElements(physGroupStage,
-                                      new String[] { "e1" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        
-        Table physGroup1 = createPhysicalGroup("MatTable1", physModel); //$NON-NLS-1$
-        createElements(physGroup1,
-                                      new String[] { "e1" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        
-        Table physGroupStage1 = createPhysicalGroup("MatStage1", physModel); //$NON-NLS-1$
-        createElements(physGroupStage,
-                                      new String[] { "e1" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        
-        Table physGroup_virtSrc = createPhysicalGroup("MatSrc", physModel_virtSrc); //$NON-NLS-1$
-        createElements(physGroup_virtSrc,
-                                      new String[] { "X" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        
-        QueryNode virtTrans = new QueryNode("MatView", "SELECT x as e1 FROM MatSrc.MatSrc");         //$NON-NLS-1$ //$NON-NLS-2$
-        Table virtGroup = createVirtualGroup("MatView", virtModel, virtTrans); //$NON-NLS-1$
-        createElements(virtGroup,
-                                      new String[] { "e1" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-       
-        virtGroup.setMaterialized(true);
-        virtGroup.setMaterializedTable(physGroup);
-        virtGroup.setMaterializedStageTable(physGroupStage);
-        
-        //add one virtual group that uses the materialized group in transformation with NOCACHE option
-        QueryNode vTrans = new QueryNode("VGroup", "SELECT e1 FROM MatView.MatView option NOCACHE");         //$NON-NLS-1$ //$NON-NLS-2$
-        Table vGroup = createVirtualGroup("VGroup", virtModel, vTrans); //$NON-NLS-1$
-        createElements(vGroup,
-                                      new String[] { "e1" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        
-        QueryNode virtTrans1 = new QueryNode("MatView1", "SELECT e1 FROM MatView.MatView where e1 = 1");         //$NON-NLS-1$ //$NON-NLS-2$
-        Table virtGroup1 = createVirtualGroup("MatView1", virtModel, virtTrans1); //$NON-NLS-1$
-        createElements(virtGroup1,
-                                      new String[] { "e1" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        
-        virtGroup1.setMaterializedTable(physGroup1);
-        virtGroup1.setMaterializedStageTable(physGroupStage1);
-
-        QueryNode vTrans2 = new QueryNode("VGroup2", "SELECT x FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
-        Table vGroup2 = createVirtualGroup("VGroup2", virtModel, vTrans2); //$NON-NLS-1$
-        vGroup2.setMaterialized(true);
-        createElements(vGroup2,
-                                      new String[] { "x" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        
-        //covering index
-        QueryNode vTrans3 = new QueryNode("VGroup3", "SELECT x, 'z' || substring(x, 2) as y FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
-        Table vGroup3 = createVirtualGroup("VGroup3", virtModel, vTrans3); //$NON-NLS-1$
-        vGroup3.setMaterialized(true);
-        List<Column> vElements3 = createElements(vGroup3,
-                                      new String[] { "x", "y" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        
-        createKey(KeyRecord.Type.Primary, "pk", vGroup3, vElements3.subList(0, 1));
-        createKey(KeyRecord.Type.Index, "idx", vGroup3, vElements3.subList(1, 2));
-
-        QueryNode vTrans4 = new QueryNode("VGroup4", "/*+ cache(ttl:100) */ SELECT x FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
-        Table vGroup4 = createVirtualGroup("VGroup4", virtModel, vTrans4); //$NON-NLS-1$
-        vGroup4.setMaterialized(true);
-        createElements(vGroup4,
-                                      new String[] { "x" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        
-        //non-covering index
-        QueryNode vTrans5 = new QueryNode("VGroup5", "SELECT x, 'z' || substring(x, 2) as y, 1 as z FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
-        Table vGroup5 = createVirtualGroup("VGroup5", virtModel, vTrans5); //$NON-NLS-1$
-        vGroup5.setMaterialized(true);
-        List<Column> vElements5 = createElements(vGroup5,
-                                      new String[] { "x", "y", "z" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
-        
-        createKey(KeyRecord.Type.Primary, "pk", vGroup5, vElements5.subList(0, 1));
-        createKey(KeyRecord.Type.Index, "idx", vGroup5, vElements5.subList(1, 2));
-        
-        //no pk
-        QueryNode vTrans6 = new QueryNode("VGroup6", "SELECT x, 'z' || substring(x, 2) as y FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
-        Table vGroup6 = createVirtualGroup("VGroup6", virtModel, vTrans6); //$NON-NLS-1$
-        vGroup6.setMaterialized(true);
-        List<Column> vElements6 = createElements(vGroup6,
-                                      new String[] { "x", "y" }, //$NON-NLS-1$
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        
-        createKey(KeyRecord.Type.Index, "idx", vGroup6, vElements6.subList(1, 2));
-        
-        Schema sp = createVirtualModel("sp", metadataStore); //$NON-NLS-1$
-        ColumnSet<Procedure> rs = createResultSet("sp1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        ProcedureParameter param = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
-        param.setNullType(NullType.Nullable);
-        QueryNode sp1qn = new QueryNode("sp1", "/*+ cache */ CREATE VIRTUAL PROCEDURE BEGIN SELECT x as StringKey from matsrc where x = param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        Procedure vsp5 = createVirtualProcedure("sp1", sp, Arrays.asList(param), sp1qn); //$NON-NLS-1$
-        vsp5.setResultSet(rs);
-
-        return createTransformationMetadata(metadataStore, "");
-    }
-    
-	/**
-	 * Create primary key.  The name will be used as the Object metadataID.
-	 * @param name String name of key
-	 * @param group the group for the key
-	 * @param elements the elements of the key (will be used as if they were
-	 * metadata IDs)
-	 * @return key metadata object
-	 */
-	public static KeyRecord createKey(KeyRecord.Type type, String name, Table group, List<Column> elements) {
-		KeyRecord key = new KeyRecord(type);
-		key.setName(name);
-		for (Column column : elements) {
-			key.addColumn(column);
-		}
-		switch (type) {
-		case Primary:
-			group.setPrimaryKey(key);
-			break;
-		case Index:
-			group.getIndexes().add(key);
-			break;
-		default:
-			throw new AssertionError("TODO");
-		}
-		return key;
-	}
-
-    /**
-     * Create a physical model with default settings.
-     */
-	public static Schema createPhysicalModel(String name, MetadataStore metadataStore) {
-		Schema schema = new Schema();
-		schema.setName(name);
-		metadataStore.addSchema(schema);
-		return schema;	
-	}
-	
-    /**
-     * Create a virtual model with default settings.
-     */
-	public static Schema createVirtualModel(String name, MetadataStore metadataStore) {
-		Schema schema = new Schema();
-		schema.setName(name);
-		schema.setPhysical(false);
-		metadataStore.addSchema(schema);
-		return schema;	
-	}
-	
-    /**
-     * Create a physical group with default settings.
-     * @param name Name of physical group, must match model name
-     * @param model Associated model
-     * @return FakeMetadataObject Metadata object for group
-     */
-	public static Table createPhysicalGroup(String name, Schema model, boolean fullyQualify) {
-		Table table = new Table();
-		table.setName(name);
-		model.addTable(table);
-		table.setSupportsUpdate(true);
-		table.setNameInSource((fullyQualify || name.lastIndexOf(".") == -1)? name : name.substring(name.lastIndexOf(".") + 1));  //$NON-NLS-1$ //$NON-NLS-2$
-		return table;
-	}
-
-    public static Table createPhysicalGroup(String name, Schema model) {
-    	return createPhysicalGroup(name, model, false);
-    }
-    	
-    /**
-     * Create a virtual group with default settings.
-     */
-	public static Table createVirtualGroup(String name, Schema model, QueryNode plan) {
-        Table table = new Table();
-        table.setName(name);
-        model.addTable(table);
-        table.setVirtual(true);
-        table.setSelectTransformation(plan.getQuery());
-		return table;
-	}
-
-    /**
-     * Create a virtual group that allows updates with default settings.
-     */
-	public static Table createUpdatableVirtualGroup(String name, Schema model, QueryNode plan) {
-		return createUpdatableVirtualGroup(name, model, plan, null);
-	}
-    
-    public static Table createUpdatableVirtualGroup(String name, Schema model, QueryNode plan, String updatePlan) {
-        Table table = createVirtualGroup(name, model, plan);
-        table.setUpdatePlan(updatePlan);
-        table.setSupportsUpdate(true);
-        return table;
-    }
-		
-    public static Column createElement(String name, ColumnSet<?> group, String type) { 
-        Column column = new Column();
-        column.setName(name);
-        group.addColumn(column);
-        column.setRuntimeType(type);
-        if(type.equals(DataTypeManager.DefaultDataTypes.STRING)) {  
-            column.setSearchType(SearchType.Searchable);        
-        } else if (DataTypeManager.isNonComparable(type)){
-        	column.setSearchType(SearchType.Unsearchable);
-        } else {        	
-        	column.setSearchType(SearchType.All_Except_Like);
-        }   
-        column.setNullType(NullType.Nullable);
-        column.setPosition(group.getColumns().size()); //1 based indexing
-        column.setUpdatable(true);
-        column.setLength(100);
-        column.setNameInSource(name);
-        return column; 
-    }
-    
-    /**
-     * Create a set of elements in batch 
-     */
-	public static List<Column> createElements(ColumnSet<?> group, String[] names, String[] types) { 
-		return createElementsWithDefaults(group, names, types, new String[names.length]);
-	}
-
-    /**
-     * Create a set of elements in batch 
-     */
-	public static List<Column> createElementsWithDefaults(ColumnSet<?> group, String[] names, String[] types, String[] defaults) {
-		List<Column> elements = new ArrayList<Column>();
-		
-		for(int i=0; i<names.length; i++) { 
-            Column element = createElement(names[i], group, types[i]);
-            element.setDefaultValue(defaults[i]);
-			elements.add(element);		
-		}
-		
-		return elements;
-	}	
-
-    /**
-     * Create stored procedure parameter.
-     */
-    public static ProcedureParameter createParameter(String name, int direction, String type) {
-        ProcedureParameter param = new ProcedureParameter();
-        param.setName(name);
-        switch (direction) {
-        case SPParameter.IN:
-        	param.setType(Type.In);
-        	break;
-        case SPParameter.INOUT:
-        	param.setType(Type.InOut);
-        	break;
-        case SPParameter.OUT:
-        	param.setType(Type.Out);
-        	break;
-        case SPParameter.RESULT_SET:
-        	throw new AssertionError("should not directly create a resultset param"); //$NON-NLS-1$
-        case SPParameter.RETURN_VALUE:
-        	param.setType(Type.ReturnValue);
-        	break;
-        }
-        param.setRuntimeType(type);
-        return param;
-    }
-
-    /**
-     * Create stored procedure.
-     * @param name Name of procedure, must match model name
-     * @param model Metadata object for the model
-     * @param params List of FakeMetadataObject that are the parameters for the procedure
-     * @param callableName Callable name of procedure, usually same as procedure name
-     * @return Metadata object for stored procedure
-     */
-    public static Procedure createStoredProcedure(String name, Schema model, List<ProcedureParameter> params, String callableName) {
-    	Procedure proc = new Procedure();
-    	proc.setName(name);
-    	if (params != null) {
-    		int index = 1;
-	    	for (ProcedureParameter procedureParameter : params) {
-				procedureParameter.setProcedure(proc);
-				procedureParameter.setPosition(index++);
-			}
-	    	proc.setParameters(params);
-    	}
-    	model.addProcedure(proc);
-        return proc;    
-    }
-    
-    /**
-     * Create virtual sotred procedure.
-     * @param name Name of stored query, must match model name
-     * @param model Metadata object for the model
-     * @param params List of FakeMetadataObject that are the parameters for the procedure
-     * @param queryPlan Object representing query plan
-     * @return Metadata object for stored procedure
-     */
-    public static Procedure createVirtualProcedure(String name, Schema model, List<ProcedureParameter> params, QueryNode queryPlan) {
-    	Procedure proc = createStoredProcedure(name, model, params, null);
-    	proc.setVirtual(true);
-    	proc.setQueryPlan(queryPlan.getQuery());
-        return proc;
-    }
-    
-    /**
-     * Create a result set.
-     */
-    public static ColumnSet<Procedure> createResultSet(String name, String[] colNames, String[] colTypes) {
-    	ColumnSet<Procedure> rs = new ColumnSet<Procedure>();
-    	rs.setName(name);
-        for(Column column : createElements(rs, colNames, colTypes)) {
-        	column.setParent(rs);
-        }
-        return rs;
-    }
-
-}

Copied: tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java (from rev 2707, branches/7.2.x/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,626 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.unittest;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.ColumnSet;
+import org.teiid.metadata.KeyRecord;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.ProcedureParameter;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.BaseColumn.NullType;
+import org.teiid.metadata.Column.SearchType;
+import org.teiid.metadata.ProcedureParameter.Type;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.sql.lang.SPParameter;
+
+ at SuppressWarnings("nls")
+public class RealMetadataFactory {
+
+    private static TransformationMetadata CACHED_BQT = exampleBQT();
+        
+	private RealMetadataFactory() { }
+	
+    public static TransformationMetadata exampleBQTCached() {
+        return CACHED_BQT;
+    }
+    
+    public static TransformationMetadata exampleBQT() {
+    	MetadataStore metadataStore = new MetadataStore();
+    	
+        Schema bqt1 = createPhysicalModel("BQT1", metadataStore); //$NON-NLS-1$
+        Schema bqt2 = createPhysicalModel("BQT2", metadataStore); //$NON-NLS-1$
+        Schema bqt3 = createPhysicalModel("BQT3", metadataStore); //$NON-NLS-1$
+        Schema lob = createPhysicalModel("LOB", metadataStore); //$NON-NLS-1$
+        Schema vqt = createVirtualModel("VQT", metadataStore); //$NON-NLS-1$
+        Schema bvqt = createVirtualModel("BQT_V", metadataStore); //$NON-NLS-1$
+        Schema bvqt2 = createVirtualModel("BQT2_V", metadataStore); //$NON-NLS-1$
+        
+        // Create physical groups
+        Table bqt1SmallA = createPhysicalGroup("SmallA", bqt1); //$NON-NLS-1$
+        Table bqt1SmallB = createPhysicalGroup("SmallB", bqt1); //$NON-NLS-1$
+        Table bqt1MediumA = createPhysicalGroup("MediumA", bqt1); //$NON-NLS-1$
+        Table bqt1MediumB = createPhysicalGroup("MediumB", bqt1); //$NON-NLS-1$
+        Table bqt2SmallA = createPhysicalGroup("SmallA", bqt2); //$NON-NLS-1$
+        Table bqt2SmallB = createPhysicalGroup("SmallB", bqt2); //$NON-NLS-1$
+        Table bqt2MediumA = createPhysicalGroup("MediumA", bqt2); //$NON-NLS-1$
+        Table bqt2MediumB = createPhysicalGroup("MediumB", bqt2); //$NON-NLS-1$
+        Table bqt3SmallA = createPhysicalGroup("SmallA", bqt3); //$NON-NLS-1$
+        Table bqt3SmallB = createPhysicalGroup("SmallB", bqt3); //$NON-NLS-1$
+        Table bqt3MediumA = createPhysicalGroup("MediumA", bqt3); //$NON-NLS-1$
+        Table bqt3MediumB = createPhysicalGroup("MediumB", bqt3); //$NON-NLS-1$
+        Table lobTable = createPhysicalGroup("LobTbl", lob); //$NON-NLS-1$
+        Table library = createPhysicalGroup("LOB_TESTING_ONE", lob); //$NON-NLS-1$
+        
+        createElements( library, new String[] { "CLOB_COLUMN", "BLOB_COLUMN", "KEY_EMULATOR" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        		new String[] { DataTypeManager.DefaultDataTypes.CLOB, DataTypeManager.DefaultDataTypes.BLOB, DataTypeManager.DefaultDataTypes.INTEGER }); 
+
+        // Create virtual groups
+        QueryNode vqtn1 = new QueryNode("VQT.SmallA", "SELECT * FROM BQT1.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg1 = createUpdatableVirtualGroup("SmallA", vqt, vqtn1); //$NON-NLS-1$
+        
+        QueryNode vqtn2 = new QueryNode("VQT.SmallB", "SELECT Concat(stringKey, stringNum) as a12345 FROM BQT1.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2 = createUpdatableVirtualGroup("SmallB", vqt, vqtn2); //$NON-NLS-1$        
+
+        // Case 2589
+        QueryNode vqtn2589 = new QueryNode("VQT.SmallA_2589", "SELECT * FROM BQT1.SmallA WHERE StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2589 = createVirtualGroup("SmallA_2589", vqt, vqtn2589); //$NON-NLS-1$
+
+        QueryNode vqtn2589a = new QueryNode("VQT.SmallA_2589a", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.IntKey = SmallB.IntKey WHERE SmallA.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2589a = createVirtualGroup("SmallA_2589a", vqt, vqtn2589a); //$NON-NLS-1$
+
+        QueryNode vqtn2589b = new QueryNode("VQT.SmallA_2589b", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2589b = createVirtualGroup("SmallA_2589b", vqt, vqtn2589b); //$NON-NLS-1$
+
+        QueryNode vqtn2589c = new QueryNode("VQT.SmallA_2589c", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE concat(SmallA.StringNum, SmallB.StringNum) = '1010'"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2589c = createVirtualGroup("SmallA_2589c", vqt, vqtn2589c); //$NON-NLS-1$
+        
+        QueryNode vqtn2589d = new QueryNode("VQT.SmallA_2589d", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10' AND SmallA.IntNum = 10"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2589d = createVirtualGroup("SmallA_2589d", vqt, vqtn2589d); //$NON-NLS-1$
+
+        QueryNode vqtn2589f = new QueryNode("VQT.SmallA_2589f", "SELECT * FROM VQT.SmallA_2589"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2589f = createVirtualGroup("SmallA_2589f", vqt, vqtn2589f); //$NON-NLS-1$
+
+        QueryNode vqtn2589g = new QueryNode("VQT.SmallA_2589g", "SELECT * FROM VQT.SmallA_2589b"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2589g = createVirtualGroup("SmallA_2589g", vqt, vqtn2589g); //$NON-NLS-1$
+
+        QueryNode vqtn2589h = new QueryNode("VQT.SmallA_2589h", "SELECT VQT.SmallA_2589.* FROM VQT.SmallA_2589 INNER JOIN BQT1.SmallB ON VQT.SmallA_2589.StringKey = SmallB.StringKey"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2589h = createVirtualGroup("SmallA_2589h", vqt, vqtn2589h); //$NON-NLS-1$
+        
+        QueryNode vqtn2589i = new QueryNode("VQT.SmallA_2589i", "SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10' AND SmallB.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg2589i = createVirtualGroup("SmallA_2589i", vqt, vqtn2589i); //$NON-NLS-1$
+
+        // defect 15355
+        QueryNode vqtn15355  = new QueryNode("VQT.Defect15355", "SELECT convert(IntKey, string) as StringKey, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg15355  = createVirtualGroup("Defect15355", vqt, vqtn15355); //$NON-NLS-1$
+        QueryNode vqtn15355a  = new QueryNode("VQT.Defect15355a", "SELECT StringKey, StringNum, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, StringNum, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg15355a  = createVirtualGroup("Defect15355a", vqt, vqtn15355a); //$NON-NLS-1$
+        QueryNode vqtn15355b  = new QueryNode("VQT.Defect15355b", "SELECT convert(IntKey, string) as IntKey, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vqtg15355b  = createVirtualGroup("Defect15355b", vqt, vqtn15355b); //$NON-NLS-1$
+        
+        QueryNode bvqtn1 = new QueryNode("BQT_V.BQT_V", "SELECT a.* FROM BQT1.SMALLA AS a WHERE a.INTNUM = (SELECT MIN(b.INTNUM) FROM BQT1.SMALLA AS b WHERE b.INTKEY = a.IntKey ) OPTION MAKEDEP a"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table bvqtg1 = createUpdatableVirtualGroup("BQT_V", bvqt, bvqtn1); //$NON-NLS-1$
+        QueryNode bvqt2n1 = new QueryNode("BQT2_V.BQT2_V", "SELECT BQT2.SmallA.* FROM BQT2.SmallA, BQT_V.BQT_V WHERE BQT2.SmallA.IntKey = BQT_V.BQT_V.IntKey"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table bvqt2g1 = createUpdatableVirtualGroup("BQT2_V", bvqt2, bvqt2n1); //$NON-NLS-1$
+
+     // Create physical elements
+        String[] elemNames = new String[] { 
+             "IntKey", "StringKey",  //$NON-NLS-1$ //$NON-NLS-2$
+             "IntNum", "StringNum",  //$NON-NLS-1$ //$NON-NLS-2$
+             "FloatNum", "LongNum",  //$NON-NLS-1$ //$NON-NLS-2$
+             "DoubleNum", "ByteNum",  //$NON-NLS-1$ //$NON-NLS-2$
+             "DateValue", "TimeValue",  //$NON-NLS-1$ //$NON-NLS-2$
+             "TimestampValue", "BooleanValue",  //$NON-NLS-1$ //$NON-NLS-2$
+             "CharValue", "ShortValue",  //$NON-NLS-1$ //$NON-NLS-2$
+             "BigIntegerValue", "BigDecimalValue",  //$NON-NLS-1$ //$NON-NLS-2$
+             "ObjectValue" }; //$NON-NLS-1$
+         String[] elemTypes = new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, 
+                             DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, 
+                             DataTypeManager.DefaultDataTypes.FLOAT, DataTypeManager.DefaultDataTypes.LONG, 
+                             DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.BYTE, 
+                             DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, 
+                             DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.DefaultDataTypes.BOOLEAN, 
+                             DataTypeManager.DefaultDataTypes.CHAR, DataTypeManager.DefaultDataTypes.SHORT, 
+                             DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL, 
+                             DataTypeManager.DefaultDataTypes.OBJECT };
+        
+        List<Column> bqt1SmallAe = createElements(bqt1SmallA, elemNames, elemTypes);
+        bqt1SmallAe.get(1).setNativeType("char"); //$NON-NLS-1$
+        createElements(bqt1SmallB, elemNames, elemTypes);
+        createElements(bqt1MediumA, elemNames, elemTypes);
+        createElements(bqt1MediumB, elemNames, elemTypes);
+        createElements(bqt2SmallA, elemNames, elemTypes);
+        createElements(bqt2SmallB, elemNames, elemTypes);
+        createElements(bqt2MediumA, elemNames, elemTypes);
+        createElements(bqt2MediumB, elemNames, elemTypes);                
+        createElements(bqt3SmallA, elemNames, elemTypes);
+        createElements(bqt3SmallB, elemNames, elemTypes);
+        createElements(bqt3MediumA, elemNames, elemTypes);
+        createElements(bqt3MediumB, elemNames, elemTypes);
+        createElements(lobTable, new String[] {"ClobValue"}, new String[] {DataTypeManager.DefaultDataTypes.CLOB}); //$NON-NLS-1$
+        
+        // Create virtual elements
+        createElements(vqtg1, elemNames, elemTypes);        
+        createElements(vqtg2, new String[] {"a12345"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});  //$NON-NLS-1$
+        createElements(vqtg15355, new String[] {"StringKey", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER});         //$NON-NLS-1$ //$NON-NLS-2$
+        createElements(vqtg15355a, new String[] {"StringKey", "StringNum", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER});         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        createElements(vqtg15355b, new String[] {"IntKey", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER});         //$NON-NLS-1$ //$NON-NLS-2$
+        createElements(vqtg2589, elemNames, elemTypes);        
+        createElements(vqtg2589a, elemNames, elemTypes);        
+        createElements(vqtg2589b, elemNames, elemTypes);        
+        createElements(vqtg2589c, elemNames, elemTypes);        
+        createElements(vqtg2589d, elemNames, elemTypes);        
+        createElements(vqtg2589f, elemNames, elemTypes);        
+        createElements(vqtg2589g, elemNames, elemTypes);        
+        createElements(vqtg2589h, elemNames, elemTypes);        
+        createElements(vqtg2589i, elemNames, elemTypes);
+        createElements(bvqtg1, elemNames, elemTypes);        
+        createElements(bvqt2g1, elemNames, elemTypes);        
+
+     // Add stored procedure
+        Schema pm1 = createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+        ProcedureParameter rs1p1 = createParameter("intkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);         //$NON-NLS-1$
+        ColumnSet<Procedure> rs1 = createResultSet("rs1", new String[] { "IntKey", "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        Procedure spTest5 = createStoredProcedure("spTest5", pm1, Arrays.asList(rs1p1), "spTest5"); //$NON-NLS-1$ //$NON-NLS-2$
+        spTest5.setResultSet(rs1);
+
+        Schema pm2 = createPhysicalModel("pm2", metadataStore); //$NON-NLS-1$
+        ProcedureParameter rs2p1 = createParameter("inkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        ProcedureParameter rs2p2 = createParameter("outkey", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER);                 //$NON-NLS-1$
+        ColumnSet<Procedure> rs2 = createResultSet("rs2", new String[] { "IntKey", "StringKey"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        Procedure spTest8 = createStoredProcedure("spTest8", pm2, Arrays.asList(rs2p1, rs2p2), "spTest8"); //$NON-NLS-1$ //$NON-NLS-2$
+        spTest8.setResultSet(rs2);
+        
+        ProcedureParameter rs2p2a = createParameter("outkey", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER);                 //$NON-NLS-1$
+        ColumnSet<Procedure> rs2a = createResultSet("rs2", new String[] { "IntKey", "StringKey"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        Procedure spTest8a = createStoredProcedure("spTest8a", pm2, Arrays.asList(rs2p2a), "spTest8a"); //$NON-NLS-1$ //$NON-NLS-2$
+        spTest8a.setResultSet(rs2a);
+        
+        Schema pm4 = createPhysicalModel("pm4", metadataStore); //$NON-NLS-1$
+        ProcedureParameter rs4p1 = createParameter("ret", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        ProcedureParameter rs4p2 = createParameter("inkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        createStoredProcedure("spTest9", pm4, Arrays.asList(rs4p1, rs4p2), "spTest9"); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        Schema pm3 = createPhysicalModel("pm3", metadataStore); //$NON-NLS-1$
+        ProcedureParameter rs3p1 = createParameter("inkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        ProcedureParameter rs3p2 = createParameter("outkey", ParameterInfo.INOUT, DataTypeManager.DefaultDataTypes.INTEGER);                 //$NON-NLS-1$
+        ColumnSet<Procedure> rs3 = createResultSet("rs3", new String[] { "IntKey", "StringKey"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        Procedure spTest11 = createStoredProcedure("spTest11", pm3, Arrays.asList(rs3p1, rs3p2), "spTest11"); //$NON-NLS-1$ //$NON-NLS-2$
+        spTest11.setResultSet(rs3);
+        
+        //add virtual stored procedures 
+        Schema mmspTest1 = createVirtualModel("mmspTest1", metadataStore); //$NON-NLS-1$
+        ColumnSet<Procedure> vsprs1 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode vspqn1 = new QueryNode("vsp1", "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor BEGIN x= intKeyCursor.intkey - 1; END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp1 = createVirtualProcedure("MMSP1", mmspTest1, null, vspqn1); //$NON-NLS-1$
+        vsp1.setResultSet(vsprs1);
+
+        ColumnSet<Procedure> vsprs2 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode vspqn2 = new QueryNode("vsp2", "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor1 BEGIN LOOP ON (SELECT intkey FROM bqt1.smallB) AS intKeyCursor2 BEGIN x= intKeyCursor1.intkey - intKeyCursor2.intkey; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp2 = createVirtualProcedure("MMSP2", mmspTest1, null, vspqn2); //$NON-NLS-1$
+        vsp2.setResultSet(vsprs2);
+
+        ColumnSet<Procedure> vsprs3 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode vspqn3 = new QueryNode("vsp3", "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor BEGIN x= intKeyCursor.intkey - 1; if(x = 25) BEGIN BREAK; END ELSE BEGIN CONTINUE; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp3 = createVirtualProcedure("MMSP3", mmspTest1, null, vspqn3); //$NON-NLS-1$
+        vsp3.setResultSet(vsprs3);
+
+        ColumnSet<Procedure> vsprs4 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode vspqn4 = new QueryNode("vsp4", "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE(x < 50) BEGIN x= x + 1; if(x = 25) BEGIN BREAK; END ELSE BEGIN CONTINUE; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp4 = createVirtualProcedure("MMSP4", mmspTest1, null, vspqn4); //$NON-NLS-1$
+        vsp4.setResultSet(vsprs4);
+        
+        ColumnSet<Procedure> vsprs5 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter vsp5p1 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        QueryNode vspqn5 = new QueryNode("vsp5", "CREATE VIRTUAL PROCEDURE BEGIN SELECT 0; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp5 = createVirtualProcedure("MMSP5", mmspTest1, Arrays.asList(vsp5p1), vspqn5); //$NON-NLS-1$
+        vsp5.setResultSet(vsprs5);
+
+        ColumnSet<Procedure> vsprs6 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter vsp6p1 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        QueryNode vspqn6 = new QueryNode("vsp6", "CREATE VIRTUAL PROCEDURE BEGIN SELECT p1 as StringKey; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp6 = createVirtualProcedure("MMSP6", mmspTest1, Arrays.asList(vsp6p1), vspqn6); //$NON-NLS-1$
+        vsp6.setResultSet(vsprs6);
+        
+        createStoredProcedure("spRetOut", pm4, Arrays.asList(createParameter("ret", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER),
+        		createParameter("x", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER)), "spRetOut"); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        ColumnSet<Procedure> vsprs7 = createResultSet("TEIIDSP7.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter vsp7p1 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn7 = new QueryNode("TEIIDSP7", "CREATE VIRTUAL PROCEDURE BEGIN declare integer x; x = exec spTest9(p1); declare integer y; exec spTest11(inkey=>x, outkey=>y); select convert(x, string) || y; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp7 = createVirtualProcedure("TEIIDSP7", mmspTest1, Arrays.asList(vsp7p1), vspqn7); //$NON-NLS-1$
+        vsp7.setResultSet(vsprs7);
+        
+    	return createTransformationMetadata(metadataStore, "bqt"); 
+    }
+
+	public static TransformationMetadata createTransformationMetadata(
+			MetadataStore metadataStore, String vdbName) {
+		CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
+    	VDBMetaData vdbMetaData = new VDBMetaData();
+    	vdbMetaData.setName(vdbName); //$NON-NLS-1$
+    	vdbMetaData.setVersion(1);
+    	for (Schema schema : metadataStore.getSchemas().values()) {
+			vdbMetaData.addModel(FakeMetadataFactory.createModel(schema.getName(), schema.isPhysical()));
+		}
+    	return new TransformationMetadata(vdbMetaData, store, null, null, FakeMetadataFactory.SFM.getSystemFunctions());
+	}
+    
+    /** 
+     * Metadata for Materialized Views
+     * @return
+     * @since 4.2
+     */
+    public static QueryMetadataInterface exampleMaterializedView() {
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema virtModel = createVirtualModel("MatView", metadataStore); //$NON-NLS-1$
+        Schema physModel = createPhysicalModel("MatTable", metadataStore); //$NON-NLS-1$
+        Schema physModel_virtSrc = createPhysicalModel("MatSrc", metadataStore); //$NON-NLS-1$
+        
+        Table physTable = createPhysicalGroup("info", physModel); //$NON-NLS-1$
+        createElements(physTable,
+                                      new String[] { "e1", "e2", "e3"}, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+        
+        Table physGroup = createPhysicalGroup("MatTable", physModel); //$NON-NLS-1$
+        createElements(physGroup,
+                                      new String[] { "e1" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+        
+        Table physGroupStage = createPhysicalGroup("MatStage", physModel); //$NON-NLS-1$
+        createElements(physGroupStage,
+                                      new String[] { "e1" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+        
+        Table physGroup1 = createPhysicalGroup("MatTable1", physModel); //$NON-NLS-1$
+        createElements(physGroup1,
+                                      new String[] { "e1" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+        
+        Table physGroupStage1 = createPhysicalGroup("MatStage1", physModel); //$NON-NLS-1$
+        createElements(physGroupStage,
+                                      new String[] { "e1" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+        
+        Table physGroup_virtSrc = createPhysicalGroup("MatSrc", physModel_virtSrc); //$NON-NLS-1$
+        createElements(physGroup_virtSrc,
+                                      new String[] { "X" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+        
+        QueryNode virtTrans = new QueryNode("MatView", "SELECT x as e1 FROM MatSrc.MatSrc");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table virtGroup = createVirtualGroup("MatView", virtModel, virtTrans); //$NON-NLS-1$
+        createElements(virtGroup,
+                                      new String[] { "e1" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+       
+        virtGroup.setMaterialized(true);
+        virtGroup.setMaterializedTable(physGroup);
+        virtGroup.setMaterializedStageTable(physGroupStage);
+        
+        //add one virtual group that uses the materialized group in transformation with NOCACHE option
+        QueryNode vTrans = new QueryNode("VGroup", "SELECT e1 FROM MatView.MatView option NOCACHE");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vGroup = createVirtualGroup("VGroup", virtModel, vTrans); //$NON-NLS-1$
+        createElements(vGroup,
+                                      new String[] { "e1" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+        
+        QueryNode virtTrans1 = new QueryNode("MatView1", "SELECT e1 FROM MatView.MatView where e1 = 1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table virtGroup1 = createVirtualGroup("MatView1", virtModel, virtTrans1); //$NON-NLS-1$
+        createElements(virtGroup1,
+                                      new String[] { "e1" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+        
+        virtGroup1.setMaterializedTable(physGroup1);
+        virtGroup1.setMaterializedStageTable(physGroupStage1);
+
+        QueryNode vTrans2 = new QueryNode("VGroup2", "SELECT x FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vGroup2 = createVirtualGroup("VGroup2", virtModel, vTrans2); //$NON-NLS-1$
+        vGroup2.setMaterialized(true);
+        createElements(vGroup2,
+                                      new String[] { "x" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+        
+        //covering index
+        QueryNode vTrans3 = new QueryNode("VGroup3", "SELECT x, 'z' || substring(x, 2) as y FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vGroup3 = createVirtualGroup("VGroup3", virtModel, vTrans3); //$NON-NLS-1$
+        vGroup3.setMaterialized(true);
+        List<Column> vElements3 = createElements(vGroup3,
+                                      new String[] { "x", "y" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+        
+        createKey(KeyRecord.Type.Primary, "pk", vGroup3, vElements3.subList(0, 1));
+        createKey(KeyRecord.Type.Index, "idx", vGroup3, vElements3.subList(1, 2));
+
+        QueryNode vTrans4 = new QueryNode("VGroup4", "/*+ cache(ttl:100) */ SELECT x FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vGroup4 = createVirtualGroup("VGroup4", virtModel, vTrans4); //$NON-NLS-1$
+        vGroup4.setMaterialized(true);
+        createElements(vGroup4,
+                                      new String[] { "x" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING});
+        
+        //non-covering index
+        QueryNode vTrans5 = new QueryNode("VGroup5", "SELECT x, 'z' || substring(x, 2) as y, 1 as z FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vGroup5 = createVirtualGroup("VGroup5", virtModel, vTrans5); //$NON-NLS-1$
+        vGroup5.setMaterialized(true);
+        List<Column> vElements5 = createElements(vGroup5,
+                                      new String[] { "x", "y", "z" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+        
+        createKey(KeyRecord.Type.Primary, "pk", vGroup5, vElements5.subList(0, 1));
+        createKey(KeyRecord.Type.Index, "idx", vGroup5, vElements5.subList(1, 2));
+        
+        //no pk
+        QueryNode vTrans6 = new QueryNode("VGroup6", "SELECT x, 'z' || substring(x, 2) as y FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vGroup6 = createVirtualGroup("VGroup6", virtModel, vTrans6); //$NON-NLS-1$
+        vGroup6.setMaterialized(true);
+        List<Column> vElements6 = createElements(vGroup6,
+                                      new String[] { "x", "y" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+        
+        createKey(KeyRecord.Type.Index, "idx", vGroup6, vElements6.subList(1, 2));
+        
+        //non-covering index
+        QueryNode vTrans7 = new QueryNode("VGroup7", "SELECT '1', 'z' || substring(x, 2) as y, 1 as z FROM matsrc");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vGroup7 = createVirtualGroup("VGroup7", virtModel, vTrans7); //$NON-NLS-1$
+        vGroup7.setMaterialized(true);
+        List<Column> vElements7 = createElements(vGroup7,
+                                      new String[] { "x", "y", "z" }, //$NON-NLS-1$
+                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+        
+        createKey(KeyRecord.Type.Primary, "pk", vGroup7, vElements7.subList(1, 2));
+        
+        Schema sp = createVirtualModel("sp", metadataStore); //$NON-NLS-1$
+        ColumnSet<Procedure> rs = createResultSet("sp1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter param = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        param.setNullType(NullType.Nullable);
+        QueryNode sp1qn = new QueryNode("sp1", "/*+ cache */ CREATE VIRTUAL PROCEDURE BEGIN SELECT x as StringKey from matsrc where x = param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp5 = createVirtualProcedure("sp1", sp, Arrays.asList(param), sp1qn); //$NON-NLS-1$
+        vsp5.setResultSet(rs);
+
+        return createTransformationMetadata(metadataStore, "");
+    }
+    
+	/**
+	 * Create primary key.  The name will be used as the Object metadataID.
+	 * @param name String name of key
+	 * @param group the group for the key
+	 * @param elements the elements of the key (will be used as if they were
+	 * metadata IDs)
+	 * @return key metadata object
+	 */
+	public static KeyRecord createKey(KeyRecord.Type type, String name, Table group, List<Column> elements) {
+		KeyRecord key = new KeyRecord(type);
+		key.setName(name);
+		for (Column column : elements) {
+			key.addColumn(column);
+		}
+		switch (type) {
+		case Primary:
+			group.setPrimaryKey(key);
+			break;
+		case Index:
+			group.getIndexes().add(key);
+			break;
+		default:
+			throw new AssertionError("TODO");
+		}
+		return key;
+	}
+
+    /**
+     * Create a physical model with default settings.
+     */
+	public static Schema createPhysicalModel(String name, MetadataStore metadataStore) {
+		Schema schema = new Schema();
+		schema.setName(name);
+		metadataStore.addSchema(schema);
+		return schema;	
+	}
+	
+    /**
+     * Create a virtual model with default settings.
+     */
+	public static Schema createVirtualModel(String name, MetadataStore metadataStore) {
+		Schema schema = new Schema();
+		schema.setName(name);
+		schema.setPhysical(false);
+		metadataStore.addSchema(schema);
+		return schema;	
+	}
+	
+    /**
+     * Create a physical group with default settings.
+     * @param name Name of physical group, must match model name
+     * @param model Associated model
+     * @return FakeMetadataObject Metadata object for group
+     */
+	public static Table createPhysicalGroup(String name, Schema model, boolean fullyQualify) {
+		Table table = new Table();
+		table.setName(name);
+		model.addTable(table);
+		table.setSupportsUpdate(true);
+		table.setNameInSource((fullyQualify || name.lastIndexOf(".") == -1)? name : name.substring(name.lastIndexOf(".") + 1));  //$NON-NLS-1$ //$NON-NLS-2$
+		return table;
+	}
+
+    public static Table createPhysicalGroup(String name, Schema model) {
+    	return createPhysicalGroup(name, model, false);
+    }
+    	
+    /**
+     * Create a virtual group with default settings.
+     */
+	public static Table createVirtualGroup(String name, Schema model, QueryNode plan) {
+        Table table = new Table();
+        table.setName(name);
+        model.addTable(table);
+        table.setVirtual(true);
+        table.setSelectTransformation(plan.getQuery());
+		return table;
+	}
+
+    /**
+     * Create a virtual group that allows updates with default settings.
+     */
+	public static Table createUpdatableVirtualGroup(String name, Schema model, QueryNode plan) {
+		return createUpdatableVirtualGroup(name, model, plan, null);
+	}
+    
+    public static Table createUpdatableVirtualGroup(String name, Schema model, QueryNode plan, String updatePlan) {
+        Table table = createVirtualGroup(name, model, plan);
+        table.setUpdatePlan(updatePlan);
+        table.setSupportsUpdate(true);
+        return table;
+    }
+		
+    public static Column createElement(String name, ColumnSet<?> group, String type) { 
+        Column column = new Column();
+        column.setName(name);
+        group.addColumn(column);
+        column.setRuntimeType(type);
+        if(type.equals(DataTypeManager.DefaultDataTypes.STRING)) {  
+            column.setSearchType(SearchType.Searchable);        
+        } else if (DataTypeManager.isNonComparable(type)){
+        	column.setSearchType(SearchType.Unsearchable);
+        } else {        	
+        	column.setSearchType(SearchType.All_Except_Like);
+        }   
+        column.setNullType(NullType.Nullable);
+        column.setPosition(group.getColumns().size()); //1 based indexing
+        column.setUpdatable(true);
+        column.setLength(100);
+        column.setNameInSource(name);
+        return column; 
+    }
+    
+    /**
+     * Create a set of elements in batch 
+     */
+	public static List<Column> createElements(ColumnSet<?> group, String[] names, String[] types) { 
+		return createElementsWithDefaults(group, names, types, new String[names.length]);
+	}
+
+    /**
+     * Create a set of elements in batch 
+     */
+	public static List<Column> createElementsWithDefaults(ColumnSet<?> group, String[] names, String[] types, String[] defaults) {
+		List<Column> elements = new ArrayList<Column>();
+		
+		for(int i=0; i<names.length; i++) { 
+            Column element = createElement(names[i], group, types[i]);
+            element.setDefaultValue(defaults[i]);
+			elements.add(element);		
+		}
+		
+		return elements;
+	}	
+
+    /**
+     * Create stored procedure parameter.
+     */
+    public static ProcedureParameter createParameter(String name, int direction, String type) {
+        ProcedureParameter param = new ProcedureParameter();
+        param.setName(name);
+        switch (direction) {
+        case SPParameter.IN:
+        	param.setType(Type.In);
+        	break;
+        case SPParameter.INOUT:
+        	param.setType(Type.InOut);
+        	break;
+        case SPParameter.OUT:
+        	param.setType(Type.Out);
+        	break;
+        case SPParameter.RESULT_SET:
+        	throw new AssertionError("should not directly create a resultset param"); //$NON-NLS-1$
+        case SPParameter.RETURN_VALUE:
+        	param.setType(Type.ReturnValue);
+        	break;
+        }
+        param.setRuntimeType(type);
+        return param;
+    }
+
+    /**
+     * Create stored procedure.
+     * @param name Name of procedure, must match model name
+     * @param model Metadata object for the model
+     * @param params List of FakeMetadataObject that are the parameters for the procedure
+     * @param callableName Callable name of procedure, usually same as procedure name
+     * @return Metadata object for stored procedure
+     */
+    public static Procedure createStoredProcedure(String name, Schema model, List<ProcedureParameter> params, String callableName) {
+    	Procedure proc = new Procedure();
+    	proc.setName(name);
+    	if (params != null) {
+    		int index = 1;
+	    	for (ProcedureParameter procedureParameter : params) {
+				procedureParameter.setProcedure(proc);
+				procedureParameter.setPosition(index++);
+			}
+	    	proc.setParameters(params);
+    	}
+    	model.addProcedure(proc);
+        return proc;    
+    }
+    
+    /**
+     * Create virtual sotred procedure.
+     * @param name Name of stored query, must match model name
+     * @param model Metadata object for the model
+     * @param params List of FakeMetadataObject that are the parameters for the procedure
+     * @param queryPlan Object representing query plan
+     * @return Metadata object for stored procedure
+     */
+    public static Procedure createVirtualProcedure(String name, Schema model, List<ProcedureParameter> params, QueryNode queryPlan) {
+    	Procedure proc = createStoredProcedure(name, model, params, null);
+    	proc.setVirtual(true);
+    	proc.setQueryPlan(queryPlan.getQuery());
+        return proc;
+    }
+    
+    /**
+     * Create a result set.
+     */
+    public static ColumnSet<Procedure> createResultSet(String name, String[] colNames, String[] colTypes) {
+    	ColumnSet<Procedure> rs = new ColumnSet<Procedure>();
+    	rs.setName(name);
+        for(Column column : createElements(rs, colNames, colTypes)) {
+        	column.setParent(rs);
+        }
+        return rs;
+    }
+
+}

Deleted: tags/teiid-parent-7.2.0.Final/hibernate-dialect/pom.xml
===================================================================
--- branches/7.2.x/hibernate-dialect/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/hibernate-dialect/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,18 +0,0 @@
-<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">
-	<parent>
-		<artifactId>teiid-parent</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>teiid-hibernate-dialect</artifactId>
-	<name>Hibernate Dialect</name>
-	<description>Teiid Hibernate Dialect</description>
-	<dependencies>
-		<dependency>
-			<groupId>org.hibernate</groupId>
-			<artifactId>hibernate-core</artifactId>
-			<version>3.5.2-Final</version>
-		</dependency>
-	</dependencies>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/hibernate-dialect/pom.xml (from rev 2708, branches/7.2.x/hibernate-dialect/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/hibernate-dialect/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/hibernate-dialect/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,18 @@
+<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">
+	<parent>
+		<artifactId>teiid-parent</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>teiid-hibernate-dialect</artifactId>
+	<name>Hibernate Dialect</name>
+	<description>Teiid Hibernate Dialect</description>
+	<dependencies>
+		<dependency>
+			<groupId>org.hibernate</groupId>
+			<artifactId>hibernate-core</artifactId>
+			<version>3.5.2-Final</version>
+		</dependency>
+	</dependencies>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/jboss-integration/pom.xml
===================================================================
--- branches/7.2.x/jboss-integration/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/jboss-integration/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,146 +0,0 @@
-<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">
-  <parent>
-    <artifactId>teiid-parent</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <groupId>org.jboss.teiid</groupId>
-  <artifactId>teiid-jboss-integration</artifactId>
-  <name>teiid-jboss-integration</name>
-  <description>JBoss specific integration layer for teiid</description>
-  
-  <dependencies>
- 
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-runtime</artifactId>
-    </dependency>
- 
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-api</artifactId>
-    </dependency>
-               
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-cache-jbosscache</artifactId>
-    </dependency>
-                    
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-client</artifactId>
-      <scope>provided</scope>
-    </dependency>
-    
-    <dependency>
-        <groupId>javax.resource</groupId>
-        <artifactId>connector-api</artifactId>
-        <scope>provided</scope>
-    </dependency>
-    
-    <dependency>
-        <groupId>org.jboss</groupId>
-        <artifactId>jboss-reflect</artifactId>
-        <scope>provided</scope>
-    </dependency>                            
-    
-    <dependency>
-        <groupId>org.jboss.man</groupId>
-        <artifactId>jboss-managed</artifactId>
-        <scope>provided</scope>
-    </dependency>     
-    
-    <dependency>
-        <groupId>org.jboss.integration</groupId>
-        <artifactId>jboss-profileservice-spi</artifactId>
-        <scope>provided</scope>
-    </dependency>    
-
-    <dependency>
-      <groupId>org.jboss.jbossas</groupId>
-      <artifactId>jboss-as-connector</artifactId>
-      <scope>provided</scope>      
-    </dependency>
-    
-    <dependency>
-        <groupId>org.jboss.microcontainer</groupId>
-        <artifactId>jboss-aop-mc-int</artifactId>
-        <version>2.0.6.GA</version>
-        <scope>provided</scope>
-    </dependency>    
-    <dependency>
-        <groupId>org.jboss.security</groupId>
-        <artifactId>jbosssx</artifactId>
-        <version>2.0.3.SP1</version>
-        <scope>provided</scope>
-    </dependency> 
-    <!--  these for just running profile service remotely -->
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>    
-
-    <dependency>
-        <groupId>org.jboss.naming</groupId>
-        <artifactId>jnp-client</artifactId>
-        <version>5.0.3.GA</version>
-        <scope>test</scope>
-    </dependency>
-<!-- 
-    <dependency>
-        <groupId>org.jboss.aop</groupId>
-        <artifactId>jboss-aop</artifactId>
-        <classifier>client</classifier>
-        <version>2.1.1.GA</version>
-        <scope>test</scope>
-    </dependency>    
--->
-
-    <dependency>
-        <groupId>org.jboss.remoting</groupId>
-        <artifactId>jboss-remoting</artifactId>
-        <version>2.5.1</version>
-        <scope>test</scope>
-    </dependency>
-
-    <dependency>
-        <groupId>org.jboss.aspects</groupId>
-        <artifactId>jboss-security-aspects</artifactId>
-        <version>1.0.0.GA</version>
-        <scope>test</scope>
-    </dependency>
-
-    <dependency>
-        <groupId>org.jboss.aspects</groupId>
-        <artifactId>jboss-remoting-aspects</artifactId>
-        <version>1.0.1.GA</version>
-        <scope>test</scope>
-    </dependency>
-
-    <dependency>
-        <groupId>oswego-concurrent</groupId>
-        <artifactId>concurrent</artifactId>
-        <version>1.3.4-jboss-update1</version>
-        <scope>test</scope>
-    </dependency>
-
-    <dependency>
-        <groupId>org.jboss.jbossas</groupId>
-        <artifactId>jboss-as-server</artifactId>
-        <version>5.1.0.GA</version>
-        <scope>test</scope>
-    </dependency>    
-    
-    <dependency>            
-      <groupId>org.jboss.jbossas</groupId>
-      <artifactId>jboss-as-profileservice</artifactId>  
-      <version>5.1.0.GA</version>
-      <scope>test</scope>
-    </dependency>    
-
-  </dependencies>
-  
-</project>

Copied: tags/teiid-parent-7.2.0.Final/jboss-integration/pom.xml (from rev 2708, branches/7.2.x/jboss-integration/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/jboss-integration/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/jboss-integration/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,146 @@
+<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">
+  <parent>
+    <artifactId>teiid-parent</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.jboss.teiid</groupId>
+  <artifactId>teiid-jboss-integration</artifactId>
+  <name>teiid-jboss-integration</name>
+  <description>JBoss specific integration layer for teiid</description>
+  
+  <dependencies>
+ 
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-runtime</artifactId>
+    </dependency>
+ 
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-api</artifactId>
+    </dependency>
+               
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-cache-jbosscache</artifactId>
+    </dependency>
+                    
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-client</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    
+    <dependency>
+        <groupId>javax.resource</groupId>
+        <artifactId>connector-api</artifactId>
+        <scope>provided</scope>
+    </dependency>
+    
+    <dependency>
+        <groupId>org.jboss</groupId>
+        <artifactId>jboss-reflect</artifactId>
+        <scope>provided</scope>
+    </dependency>                            
+    
+    <dependency>
+        <groupId>org.jboss.man</groupId>
+        <artifactId>jboss-managed</artifactId>
+        <scope>provided</scope>
+    </dependency>     
+    
+    <dependency>
+        <groupId>org.jboss.integration</groupId>
+        <artifactId>jboss-profileservice-spi</artifactId>
+        <scope>provided</scope>
+    </dependency>    
+
+    <dependency>
+      <groupId>org.jboss.jbossas</groupId>
+      <artifactId>jboss-as-connector</artifactId>
+      <scope>provided</scope>      
+    </dependency>
+    
+    <dependency>
+        <groupId>org.jboss.microcontainer</groupId>
+        <artifactId>jboss-aop-mc-int</artifactId>
+        <version>2.0.6.GA</version>
+        <scope>provided</scope>
+    </dependency>    
+    <dependency>
+        <groupId>org.jboss.security</groupId>
+        <artifactId>jbosssx</artifactId>
+        <version>2.0.3.SP1</version>
+        <scope>provided</scope>
+    </dependency> 
+    <!--  these for just running profile service remotely -->
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>    
+
+    <dependency>
+        <groupId>org.jboss.naming</groupId>
+        <artifactId>jnp-client</artifactId>
+        <version>5.0.3.GA</version>
+        <scope>test</scope>
+    </dependency>
+<!-- 
+    <dependency>
+        <groupId>org.jboss.aop</groupId>
+        <artifactId>jboss-aop</artifactId>
+        <classifier>client</classifier>
+        <version>2.1.1.GA</version>
+        <scope>test</scope>
+    </dependency>    
+-->
+
+    <dependency>
+        <groupId>org.jboss.remoting</groupId>
+        <artifactId>jboss-remoting</artifactId>
+        <version>2.5.1</version>
+        <scope>test</scope>
+    </dependency>
+
+    <dependency>
+        <groupId>org.jboss.aspects</groupId>
+        <artifactId>jboss-security-aspects</artifactId>
+        <version>1.0.0.GA</version>
+        <scope>test</scope>
+    </dependency>
+
+    <dependency>
+        <groupId>org.jboss.aspects</groupId>
+        <artifactId>jboss-remoting-aspects</artifactId>
+        <version>1.0.1.GA</version>
+        <scope>test</scope>
+    </dependency>
+
+    <dependency>
+        <groupId>oswego-concurrent</groupId>
+        <artifactId>concurrent</artifactId>
+        <version>1.3.4-jboss-update1</version>
+        <scope>test</scope>
+    </dependency>
+
+    <dependency>
+        <groupId>org.jboss.jbossas</groupId>
+        <artifactId>jboss-as-server</artifactId>
+        <version>5.1.0.GA</version>
+        <scope>test</scope>
+    </dependency>    
+    
+    <dependency>            
+      <groupId>org.jboss.jbossas</groupId>
+      <artifactId>jboss-as-profileservice</artifactId>  
+      <version>5.1.0.GA</version>
+      <scope>test</scope>
+    </dependency>    
+
+  </dependencies>
+  
+</project>

Deleted: tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
===================================================================
--- branches/7.2.x/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,589 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.jboss.deployers;
-
-import java.io.Serializable;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.SQLException;
-import java.sql.SQLXML;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.resource.spi.XATerminator;
-import javax.resource.spi.work.WorkManager;
-import javax.security.auth.login.LoginException;
-import javax.transaction.TransactionManager;
-
-import org.jboss.managed.api.ManagedOperation.Impact;
-import org.jboss.managed.api.annotation.ManagementComponent;
-import org.jboss.managed.api.annotation.ManagementObject;
-import org.jboss.managed.api.annotation.ManagementOperation;
-import org.jboss.managed.api.annotation.ManagementParameter;
-import org.jboss.managed.api.annotation.ManagementProperties;
-import org.jboss.managed.api.annotation.ManagementProperty;
-import org.jboss.managed.api.annotation.ViewUse;
-import org.jboss.profileservice.spi.ProfileService;
-import org.jboss.util.naming.Util;
-import org.teiid.adminapi.Admin;
-import org.teiid.adminapi.AdminComponentException;
-import org.teiid.adminapi.AdminException;
-import org.teiid.adminapi.AdminProcessingException;
-import org.teiid.adminapi.Admin.Cache;
-import org.teiid.adminapi.impl.CacheStatisticsMetadata;
-import org.teiid.adminapi.impl.DQPManagement;
-import org.teiid.adminapi.impl.RequestMetadata;
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
-import org.teiid.adminapi.jboss.AdminProvider;
-import org.teiid.cache.CacheFactory;
-import org.teiid.client.DQP;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.client.security.ILogon;
-import org.teiid.client.security.InvalidSessionException;
-import org.teiid.client.util.ExceptionUtil;
-import org.teiid.client.util.ResultsFuture;
-import org.teiid.core.ComponentNotFoundException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.deployers.VDBLifeCycleListener;
-import org.teiid.deployers.VDBRepository;
-import org.teiid.dqp.internal.process.DQPConfiguration;
-import org.teiid.dqp.internal.process.DQPCore;
-import org.teiid.dqp.internal.process.DQPWorkContext;
-import org.teiid.dqp.internal.process.TransactionServerImpl;
-import org.teiid.dqp.service.BufferService;
-import org.teiid.dqp.service.SessionService;
-import org.teiid.dqp.service.SessionServiceException;
-import org.teiid.dqp.service.TransactionService;
-import org.teiid.jboss.IntegrationPlugin;
-import org.teiid.logging.Log4jListener;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.logging.MessageLevel;
-import org.teiid.net.TeiidURL;
-import org.teiid.security.SecurityHelper;
-import org.teiid.transport.ClientServiceRegistry;
-import org.teiid.transport.ClientServiceRegistryImpl;
-import org.teiid.transport.LogonImpl;
-import org.teiid.transport.ODBCSocketListener;
-import org.teiid.transport.SocketConfiguration;
-import org.teiid.transport.SocketListener;
-
-
- at ManagementObject(name="RuntimeEngineDeployer", isRuntime=true, componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
-public class RuntimeEngineDeployer extends DQPConfiguration implements DQPManagement, Serializable , ClientServiceRegistry  {
-	private static final long serialVersionUID = -4676205340262775388L;
-	
-	private transient SocketConfiguration jdbcSocketConfiguration;
-	private transient SocketConfiguration adminSocketConfiguration;
-	private transient SocketConfiguration odbcSocketConfiguration;
-	private transient SocketListener jdbcSocket;	
-	private transient SocketListener adminSocket;
-	private transient SocketListener odbcSocket;
-	private transient TransactionServerImpl transactionServerImpl = new TransactionServerImpl();
-		
-	private transient DQPCore dqpCore = new DQPCore();
-	private transient SessionService sessionService;
-	private transient ILogon logon;
-	private transient Admin admin;
-	private transient ClientServiceRegistryImpl csr = new ClientServiceRegistryImpl();	
-	private transient VDBRepository vdbRepository;
-
-	private transient ProfileService profileService;
-	private transient String jndiName;
-	
-    public RuntimeEngineDeployer() {
-		// TODO: this does not belong here
-		LogManager.setLogListener(new Log4jListener());
-    }
-	
-	@Override
-	public <T> T getClientService(Class<T> iface)
-			throws ComponentNotFoundException {
-		return this.csr.getClientService(iface);
-	}
-	
-	@Override
-	public SecurityHelper getSecurityHelper() {
-		return this.csr.getSecurityHelper();
-	}
-	
-    public void start() {
-		dqpCore.setTransactionService((TransactionService)LogManager.createLoggingProxy(LogConstants.CTX_TXN_LOG, transactionServerImpl, new Class[] {TransactionService.class}, MessageLevel.DETAIL));
-
-    	// create the necessary services
-    	createClientServices();
-    	
-    	int offset = 0;
-    	String portBinding = System.getProperty("jboss.service.binding.set"); //$NON-NLS-1$
-    	if (portBinding != null && portBinding.startsWith("ports-")) { //$NON-NLS-1$
-    		if (portBinding.equals("ports-default")) { //$NON-NLS-1$
-    			offset = 0;
-    		}
-    		else {
-    			try {
-					offset = Integer.parseInt(portBinding.substring(portBinding.length()-2))*100;
-				} catch (NumberFormatException e) {
-					offset = 0;
-				}
-    		}
-    	}
-    	/*
-    	 * having only a single clientserviceregistry means that the admin and jdbc ports are functionally equivalent.
-    	 * this is an undocuemented feature.  Designer integration relies on this to use the same port
-    	 * for admin and preview logic.
-    	 */
-    	this.csr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
-    	this.csr.registerClientService(DQP.class, proxyService(DQP.class, this.dqpCore, LogConstants.CTX_DQP), LogConstants.CTX_DQP);
-    	this.csr.registerClientService(Admin.class, proxyService(Admin.class, admin, LogConstants.CTX_ADMIN_API), LogConstants.CTX_ADMIN_API);
-    	
-    	if (this.jdbcSocketConfiguration.isEnabled()) {
-	    	this.jdbcSocket = new SocketListener(this.jdbcSocketConfiguration, csr, this.dqpCore.getBufferManager(), offset);
-	    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_enabled","Teiid JDBC = ",(this.jdbcSocketConfiguration.getSSLConfiguration().isSslEnabled()?"mms://":"mm://")+this.jdbcSocketConfiguration.getHostAddress().getHostName()+":"+(this.jdbcSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-    	} else {
-    		LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_not_enabled", "jdbc connections")); //$NON-NLS-1$ //$NON-NLS-2$
-    	}
-    	
-    	if (this.adminSocketConfiguration.isEnabled()) {
-	    	this.adminSocket = new SocketListener(this.adminSocketConfiguration, csr, this.dqpCore.getBufferManager(), offset);
-	    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_enabled","Teiid Admin", (this.adminSocketConfiguration.getSSLConfiguration().isSslEnabled()?"mms://":"mm://")+this.adminSocketConfiguration.getHostAddress().getHostName()+":"+(this.adminSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-    	} else {
-    		LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_not_enabled", "admin connections")); //$NON-NLS-1$ //$NON-NLS-2$
-    	}
-    	
-    	if (this.odbcSocketConfiguration.isEnabled()) {
-    		this.vdbRepository.odbcEnabled();
-	    	this.odbcSocket = new ODBCSocketListener(this.odbcSocketConfiguration, csr, this.dqpCore.getBufferManager(), offset);
-	    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("odbc_enabled","Teiid ODBC - SSL=", (this.odbcSocketConfiguration.getSSLConfiguration().isSslEnabled()?"ON":"OFF")+" Host = "+this.odbcSocketConfiguration.getHostAddress().getHostName()+" Port = "+(this.odbcSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-    	} else {
-    		LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("odbc_not_enabled")); //$NON-NLS-1$
-    	}    	
-    	
-    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("engine_started", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
-    	if (jndiName != null) {
-	    	final InitialContext ic ;
-	    	try {
-	    		ic = new InitialContext() ;
-	    		Util.bind(ic, jndiName, this) ;
-	    	} catch (final NamingException ne) {
-	    		// Add jndi_failed to bundle
-	        	LogManager.logError(LogConstants.CTX_RUNTIME, ne, IntegrationPlugin.Util.getString("jndi_failed", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
-	    	}
-    	}
-    	
-    	// add vdb life cycle listeners
-		this.vdbRepository.addListener(new VDBLifeCycleListener() {
-
-			@Override
-			public void removed(String name, int version) {
-				
-			}
-			
-			@Override
-			public void added(String name, int version) {
-				// terminate all the previous sessions
-				try {
-					Collection<SessionMetadata> sessions = sessionService.getActiveSessions();
-					for (SessionMetadata session:sessions) {
-						if (name.equalsIgnoreCase(session.getVDBName()) && version == session.getVDBVersion()){
-							sessionService.terminateSession(session.getSessionId(), null);
-						}
-					}
-				} catch (SessionServiceException e) {
-					//ignore
-				}
-
-				// dump the caches. 
-				dqpCore.clearCache(Cache.PREPARED_PLAN_CACHE.toString(), name, version);
-				dqpCore.clearCache(Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString(), name, version);
-			}			
-		});    	
-	}	
-    
-    public void stop() {
-    	if (jndiName != null) {
-	    	final InitialContext ic ;
-	    	try {
-	    		ic = new InitialContext() ;
-	    		Util.unbind(ic, jndiName) ;
-	    	} catch (final NamingException ne) {
-	    	}
-    	}
-    	
-    	try {
-	    	this.dqpCore.stop();
-    	} catch(TeiidRuntimeException e) {
-    		// this bean is already shutdown
-    	}
-    	
-    	// Stop socket transport(s)
-    	if (this.jdbcSocket != null) {
-    		this.jdbcSocket.stop();
-    		this.jdbcSocket = null;
-    	}
-    	
-    	if (this.adminSocket != null) {
-    		this.adminSocket.stop();
-    		this.adminSocket = null;
-    	}    
-    	
-    	if (this.odbcSocket != null) {
-    		this.odbcSocket.stop();
-    		this.odbcSocket = null;
-    	}      	
-    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("engine_stopped", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
-    }
-    
-	private void createClientServices() {
-		
-		this.dqpCore.start(this);
-		
-		this.logon = new LogonImpl(this.sessionService, "teiid-cluster"); //$NON-NLS-1$
-		if (profileService != null) {
-			this.admin = AdminProvider.getLocal(profileService);
-		} else {
-			try {
-				this.admin = AdminProvider.getLocal();
-			} catch (AdminComponentException e) {
-				throw new TeiidRuntimeException(e.getCause());
-			}
-		}
-	}    
-	
-	/**
-	 * Creates an proxy to validate the incoming session
-	 */
-	private <T> T proxyService(final Class<T> iface, final T instance, String context) {
-
-		return iface.cast(Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {iface}, new LogManager.LoggingProxy(instance, context, MessageLevel.TRACE) {
-
-			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
-				Throwable exception = null;
-				try {
-					sessionService.validateSession(DQPWorkContext.getWorkContext().getSessionId());
-					return super.invoke(proxy, method, args);
-				} catch (InvocationTargetException e) {
-					exception = e.getTargetException();
-				} catch(Throwable t){
-					exception = t;
-				}
-				throw ExceptionUtil.convertException(method, exception);
-			}
-		}));
-	}
-	
-	public void setJdbcSocketConfiguration(SocketConfiguration socketConfig) {
-		this.jdbcSocketConfiguration = socketConfig;
-	}
-	
-	public void setAdminSocketConfiguration(SocketConfiguration socketConfig) {
-		this.adminSocketConfiguration = socketConfig;
-	}
-	
-	public void setOdbcSocketConfiguration(SocketConfiguration socketConfig) {
-		this.odbcSocketConfiguration = socketConfig;
-	}
-    
-    public void setXATerminator(XATerminator xaTerminator){
-    	this.transactionServerImpl.setXaTerminator(xaTerminator);
-    }   
-    
-    public void setTransactionManager(TransactionManager transactionManager) {
-    	this.transactionServerImpl.setTransactionManager(transactionManager);
-    }
-    
-    public void setWorkManager(WorkManager mgr) {
-    	this.transactionServerImpl.setWorkManager(mgr);
-    }
-	
-	public void setSessionService(SessionService service) {
-		this.sessionService = service;
-		service.setDqp(this.dqpCore);
-	}
-	
-	public void setBufferService(BufferService service) {
-		this.dqpCore.setBufferService(service);
-	}
-	
-	public void setSecurityHelper(SecurityHelper helper) {
-		this.csr.setSecurityHelper(helper);
-	}
-	
-	public void setVDBRepository(VDBRepository repo) {
-		this.vdbRepository = repo;
-	}
-	
-	public void setProfileService(final ProfileService profileService) {
-		this.profileService = profileService ;
-	}
-	
-	public void setJndiName(final String jndiName) {
-		this.jndiName = jndiName ;
-	}
-	
-	@Override
-    @ManagementOperation(description="Requests for perticular session", impact=Impact.ReadOnly,params={@ManagementParameter(name="sessionId",description="The session Identifier")})
-    public List<RequestMetadata> getRequestsForSession(String sessionId) {
-		return this.dqpCore.getRequestsForSession(sessionId);
-	}
-	
-	@Override
-    @ManagementOperation(description="Requests using a certain VDB", impact=Impact.ReadOnly,params={@ManagementParameter(name="vdbName",description="VDB Name"), @ManagementParameter(name="vdbVersion",description="VDB Version")})
-    public List<RequestMetadata> getRequestsUsingVDB(String vdbName, int vdbVersion) throws AdminException {
-		List<RequestMetadata> requests = new ArrayList<RequestMetadata>();
-		try {
-			Collection<SessionMetadata> sessions = this.sessionService.getActiveSessions();
-			for (SessionMetadata session:sessions) {
-				if (session.getVDBName().equals(vdbName) && session.getVDBVersion() == vdbVersion) {
-					requests.addAll(this.dqpCore.getRequestsForSession(session.getSessionId()));
-				}
-			}
-		} catch (SessionServiceException e) {
-			throw new AdminComponentException(e);
-		}
-		return requests;
-	}
-	
-    
-	@Override
-    @ManagementOperation(description="Active requests", impact=Impact.ReadOnly)
-    public List<RequestMetadata> getRequests() {
-		return this.dqpCore.getRequests();
-	}
-	
-	@Override
-    @ManagementOperation(description="Long running requests", impact=Impact.ReadOnly)
-    public List<RequestMetadata> getLongRunningRequests() {
-		return this.dqpCore.getLongRunningRequests();
-	}
-	
-	
-	@Override
-	@ManagementOperation(description="Get thread statistics worker pool", impact=Impact.ReadOnly,params={@ManagementParameter(name="identifier",description="Get thread statistics worker pool")})
-    public WorkerPoolStatisticsMetadata getWorkerPoolStatistics(){
-		return this.dqpCore.getWorkerPoolStatistics();
-	}
-	
-	@Override
-    @ManagementOperation(description="Terminate a Session",params={@ManagementParameter(name="terminateeId",description="The session to be terminated")})
-    public void terminateSession(String terminateeId) {
-		this.sessionService.terminateSession(terminateeId, DQPWorkContext.getWorkContext().getSessionId());
-    }
-    
-	@Override
-    @ManagementOperation(description="Cancel a Request",params={@ManagementParameter(name="sessionId",description="The session Identifier"), @ManagementParameter(name="executionId",description="The Execution Identifier")})    
-    public boolean cancelRequest(String sessionId, long executionId) throws AdminException {
-    	try {
-			return this.dqpCore.cancelRequest(sessionId, executionId);
-		} catch (TeiidComponentException e) {
-			throw new AdminComponentException(e);
-		}
-    }
-    
-	@Override
-    @ManagementOperation(description="Get Cache types in the system", impact=Impact.ReadOnly)
-    public Collection<String> getCacheTypes(){
-		return this.dqpCore.getCacheTypes();
-	}
-	
-	@Override
-	@ManagementOperation(description="Clear the caches in the system", impact=Impact.ReadOnly)
-	public void clearCache(String cacheType) {
-		this.dqpCore.clearCache(cacheType);
-	}
-	
-	@Override
-	@ManagementOperation(description="Get the cache statistics", impact=Impact.ReadOnly)
-	public CacheStatisticsMetadata getCacheStatistics(String cacheType) {
-		return this.dqpCore.getCacheStatistics(cacheType);
-	}
-	
-	@Override
-	@ManagementOperation(description="Active sessions", impact=Impact.ReadOnly)
-	public Collection<SessionMetadata> getActiveSessions() throws AdminException {
-		try {
-			return this.sessionService.getActiveSessions();
-		} catch (SessionServiceException e) {
-			throw new AdminComponentException(e);
-		}
-	}
-	
-	@Override
-	@ManagementProperty(description="Active session count", use={ViewUse.STATISTIC}, readOnly=true)
-	public int getActiveSessionsCount() throws AdminException{
-		try {
-			return this.sessionService.getActiveSessionsCount();
-		} catch (SessionServiceException e) {
-			throw new AdminComponentException(e);
-		}
-	}
-	
-	@Override
-	@ManagementOperation(description="Active Transactions", impact=Impact.ReadOnly)
-	public Collection<org.teiid.adminapi.Transaction> getTransactions() {
-		return this.dqpCore.getTransactions();
-	}
-	
-	@Override
-	@ManagementOperation(description="Terminate the transaction", impact=Impact.ReadOnly)
-	public void terminateTransaction(String xid) throws AdminException {
-		this.dqpCore.terminateTransaction(xid);
-	}
-
-	@Override
-    @ManagementOperation(description="Merge Two VDBs",params={@ManagementParameter(name="sourceVDBName"), at ManagementParameter(name="sourceVDBName"), @ManagementParameter(name="targetVDBName"), @ManagementParameter(name="targetVDBVersion")})
-	public void mergeVDBs(String sourceVDBName, int sourceVDBVersion,
-			String targetVDBName, int targetVDBVersion) throws AdminException {
-		this.vdbRepository.mergeVDBs(sourceVDBName, sourceVDBVersion, targetVDBName, targetVDBVersion);
-	}	
-	
-	public void setCacheFactory(CacheFactory factory) {
-		this.dqpCore.setCacheFactory(factory);
-	}
-	
-	@Override
-    @ManagementOperation(description="Execute a sql query", params={@ManagementParameter(name="vdbName"), at ManagementParameter(name="vdbVersion"), @ManagementParameter(name="command"), @ManagementParameter(name="timoutInMilli")})	
-	public List<List> executeQuery(final String vdbName, final int version, final String command, final long timoutInMilli) throws AdminException {
-		Properties properties = new Properties();
-		properties.setProperty(TeiidURL.JDBC.VDB_NAME, vdbName);
-		properties.setProperty(TeiidURL.JDBC.VDB_VERSION, String.valueOf(version));
-		
-		String user = "JOPR ADMIN"; //$NON-NLS-1$
-		LogManager.logDetail(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("admin_executing", user, command)); //$NON-NLS-1$
-		
-		SessionMetadata session = null;
-		try {
-			session = this.sessionService.createSession(user, null, "JOPR", properties, false, false); //$NON-NLS-1$
-		} catch (SessionServiceException e1) {
-			throw new AdminProcessingException(e1);
-		} catch (LoginException e1) {
-			throw new AdminProcessingException(e1);
-		}
-
-		final long requestID =  0L;
-		
-		DQPWorkContext context = new DQPWorkContext();
-		context.setSession(session);
-		
-		try {
-			return context.runInContext(new Callable<List<List>>() {
-				@Override
-				public List<List> call() throws Exception {
-					ArrayList<List> results = new ArrayList<List>();
-					
-					long start = System.currentTimeMillis();
-					RequestMessage request = new RequestMessage(command);
-					request.setExecutionId(0L);
-					request.setRowLimit(getMaxRowsFetchSize()); // this would limit the number of rows that are returned.
-					Future<ResultsMessage> message = dqpCore.executeRequest(requestID, request);
-					ResultsMessage rm = message.get(timoutInMilli, TimeUnit.MILLISECONDS);
-					
-			        if (rm.getException() != null) {
-			            throw new AdminProcessingException(rm.getException());
-			        }
-			        
-			        if (rm.isUpdateResult()) {
-			        	results.addAll(new ArrayList(Arrays.asList("update count"))); //$NON-NLS-1$
-			        	results.addAll(Arrays.asList(rm.getResults()));			        	
-			        }
-			        else {
-				        results.addAll(new ArrayList(Arrays.asList(rm.getColumnNames())));
-				        results.addAll(Arrays.asList(fixResults(rm.getResults())));
-				        
-				        while (rm.getFinalRow() == -1 || rm.getLastRow() < rm.getFinalRow()) {
-				        	long elapsed = System.currentTimeMillis() - start;
-							message = dqpCore.processCursorRequest(requestID, rm.getLastRow()+1, 1024);
-							rm = message.get(timoutInMilli-elapsed, TimeUnit.MILLISECONDS);
-							results.addAll(Arrays.asList(fixResults(rm.getResults())));
-				        }
-			        }
-
-			        long elapsed = System.currentTimeMillis() - start;
-			        ResultsFuture<?> response = dqpCore.closeRequest(requestID);
-			        response.get(timoutInMilli-elapsed, TimeUnit.MILLISECONDS);
-					return results;
-				}
-			});
-		} catch (Throwable t) {
-			throw new AdminProcessingException(t);
-		} finally {
-			try {
-				sessionService.closeSession(session.getSessionId());
-			} catch (InvalidSessionException e) { //ignore
-			}			
-		}
-	}	
-	
-	/**
-	 * Managed Object framework has bug that does not currently allow 
-	 * sending a NULL in the Collection Value, so sending literal string "null". 
-	 * If you send them as Array Value, the MO is packaged as composite object and would like 
-	 * all the elements in array to be same type which is not the case with results. 
-	 */
-	List[] fixResults(List[] rows) throws SQLException {
-		List[] newResults = new List[rows.length];
-		
-		for(int i = 0; i < rows.length; i++) {
-			List row = rows[i];
-			ArrayList newRow = new ArrayList();
-			for (Object col:row) {
-				if (col == null) {
-					newRow.add("null"); //$NON-NLS-1$ 
-				}
-				else {
-					if (col instanceof Number || col instanceof String || col instanceof Character) {
-						newRow.add(col);
-					}
-					else if (col instanceof Blob) {
-						newRow.add("blob"); //$NON-NLS-1$
-					}
-					else if (col instanceof Clob) {
-						newRow.add("clob"); //$NON-NLS-1$
-					}
-					else if (col instanceof SQLXML) {
-						SQLXML xml = (SQLXML)col;
-						newRow.add(xml.getString());
-					}
-					else {
-						newRow.add(col.toString());
-					}
-				}
-			}
-			newResults[i] = newRow;
-		}		
-		return newResults;
-	}
-}

Copied: tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java (from rev 2707, branches/7.2.x/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,589 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.jboss.deployers;
+
+import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.resource.spi.XATerminator;
+import javax.resource.spi.work.WorkManager;
+import javax.security.auth.login.LoginException;
+import javax.transaction.TransactionManager;
+
+import org.jboss.managed.api.ManagedOperation.Impact;
+import org.jboss.managed.api.annotation.ManagementComponent;
+import org.jboss.managed.api.annotation.ManagementObject;
+import org.jboss.managed.api.annotation.ManagementOperation;
+import org.jboss.managed.api.annotation.ManagementParameter;
+import org.jboss.managed.api.annotation.ManagementProperties;
+import org.jboss.managed.api.annotation.ManagementProperty;
+import org.jboss.managed.api.annotation.ViewUse;
+import org.jboss.profileservice.spi.ProfileService;
+import org.jboss.util.naming.Util;
+import org.teiid.adminapi.Admin;
+import org.teiid.adminapi.AdminComponentException;
+import org.teiid.adminapi.AdminException;
+import org.teiid.adminapi.AdminProcessingException;
+import org.teiid.adminapi.Admin.Cache;
+import org.teiid.adminapi.impl.CacheStatisticsMetadata;
+import org.teiid.adminapi.impl.DQPManagement;
+import org.teiid.adminapi.impl.RequestMetadata;
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
+import org.teiid.adminapi.jboss.AdminProvider;
+import org.teiid.cache.CacheFactory;
+import org.teiid.client.DQP;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.client.security.ILogon;
+import org.teiid.client.security.InvalidSessionException;
+import org.teiid.client.util.ExceptionUtil;
+import org.teiid.client.util.ResultsFuture;
+import org.teiid.core.ComponentNotFoundException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.deployers.VDBLifeCycleListener;
+import org.teiid.deployers.VDBRepository;
+import org.teiid.dqp.internal.process.DQPConfiguration;
+import org.teiid.dqp.internal.process.DQPCore;
+import org.teiid.dqp.internal.process.DQPWorkContext;
+import org.teiid.dqp.internal.process.TransactionServerImpl;
+import org.teiid.dqp.service.BufferService;
+import org.teiid.dqp.service.SessionService;
+import org.teiid.dqp.service.SessionServiceException;
+import org.teiid.dqp.service.TransactionService;
+import org.teiid.jboss.IntegrationPlugin;
+import org.teiid.logging.Log4jListener;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.net.TeiidURL;
+import org.teiid.security.SecurityHelper;
+import org.teiid.transport.ClientServiceRegistry;
+import org.teiid.transport.ClientServiceRegistryImpl;
+import org.teiid.transport.LogonImpl;
+import org.teiid.transport.ODBCSocketListener;
+import org.teiid.transport.SocketConfiguration;
+import org.teiid.transport.SocketListener;
+
+
+ at ManagementObject(name="RuntimeEngineDeployer", isRuntime=true, componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
+public class RuntimeEngineDeployer extends DQPConfiguration implements DQPManagement, Serializable , ClientServiceRegistry  {
+	private static final long serialVersionUID = -4676205340262775388L;
+	
+	private transient SocketConfiguration jdbcSocketConfiguration;
+	private transient SocketConfiguration adminSocketConfiguration;
+	private transient SocketConfiguration odbcSocketConfiguration;
+	private transient SocketListener jdbcSocket;	
+	private transient SocketListener adminSocket;
+	private transient SocketListener odbcSocket;
+	private transient TransactionServerImpl transactionServerImpl = new TransactionServerImpl();
+		
+	private transient DQPCore dqpCore = new DQPCore();
+	private transient SessionService sessionService;
+	private transient ILogon logon;
+	private transient Admin admin;
+	private transient ClientServiceRegistryImpl csr = new ClientServiceRegistryImpl();	
+	private transient VDBRepository vdbRepository;
+
+	private transient ProfileService profileService;
+	private transient String jndiName;
+	
+    public RuntimeEngineDeployer() {
+		// TODO: this does not belong here
+		LogManager.setLogListener(new Log4jListener());
+    }
+	
+	@Override
+	public <T> T getClientService(Class<T> iface)
+			throws ComponentNotFoundException {
+		return this.csr.getClientService(iface);
+	}
+	
+	@Override
+	public SecurityHelper getSecurityHelper() {
+		return this.csr.getSecurityHelper();
+	}
+	
+    public void start() {
+		dqpCore.setTransactionService((TransactionService)LogManager.createLoggingProxy(LogConstants.CTX_TXN_LOG, transactionServerImpl, new Class[] {TransactionService.class}, MessageLevel.DETAIL));
+
+    	// create the necessary services
+    	createClientServices();
+    	
+    	int offset = 0;
+    	String portBinding = System.getProperty("jboss.service.binding.set"); //$NON-NLS-1$
+    	if (portBinding != null && portBinding.startsWith("ports-")) { //$NON-NLS-1$
+    		if (portBinding.equals("ports-default")) { //$NON-NLS-1$
+    			offset = 0;
+    		}
+    		else {
+    			try {
+					offset = Integer.parseInt(portBinding.substring(portBinding.length()-2))*100;
+				} catch (NumberFormatException e) {
+					offset = 0;
+				}
+    		}
+    	}
+    	/*
+    	 * having only a single clientserviceregistry means that the admin and jdbc ports are functionally equivalent.
+    	 * this is an undocuemented feature.  Designer integration relies on this to use the same port
+    	 * for admin and preview logic.
+    	 */
+    	this.csr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
+    	this.csr.registerClientService(DQP.class, proxyService(DQP.class, this.dqpCore, LogConstants.CTX_DQP), LogConstants.CTX_DQP);
+    	this.csr.registerClientService(Admin.class, proxyService(Admin.class, admin, LogConstants.CTX_ADMIN_API), LogConstants.CTX_ADMIN_API);
+    	
+    	if (this.jdbcSocketConfiguration.getEnabled()) {
+	    	this.jdbcSocket = new SocketListener(this.jdbcSocketConfiguration, csr, this.dqpCore.getBufferManager(), offset);
+	    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_enabled","Teiid JDBC = ",(this.jdbcSocketConfiguration.getSSLConfiguration().isSslEnabled()?"mms://":"mm://")+this.jdbcSocketConfiguration.getHostAddress().getHostName()+":"+(this.jdbcSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+    	} else {
+    		LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_not_enabled", "jdbc connections")); //$NON-NLS-1$ //$NON-NLS-2$
+    	}
+    	
+    	if (this.adminSocketConfiguration.getEnabled()) {
+	    	this.adminSocket = new SocketListener(this.adminSocketConfiguration, csr, this.dqpCore.getBufferManager(), offset);
+	    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_enabled","Teiid Admin", (this.adminSocketConfiguration.getSSLConfiguration().isSslEnabled()?"mms://":"mm://")+this.adminSocketConfiguration.getHostAddress().getHostName()+":"+(this.adminSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+    	} else {
+    		LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_not_enabled", "admin connections")); //$NON-NLS-1$ //$NON-NLS-2$
+    	}
+    	
+    	if (this.odbcSocketConfiguration.getEnabled()) {
+    		this.vdbRepository.odbcEnabled();
+	    	this.odbcSocket = new ODBCSocketListener(this.odbcSocketConfiguration, csr, this.dqpCore.getBufferManager(), offset);
+	    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("odbc_enabled","Teiid ODBC - SSL=", (this.odbcSocketConfiguration.getSSLConfiguration().isSslEnabled()?"ON":"OFF")+" Host = "+this.odbcSocketConfiguration.getHostAddress().getHostName()+" Port = "+(this.odbcSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+    	} else {
+    		LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("odbc_not_enabled")); //$NON-NLS-1$
+    	}    	
+    	
+    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("engine_started", getRuntimeVersion(), new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
+    	if (jndiName != null) {
+	    	final InitialContext ic ;
+	    	try {
+	    		ic = new InitialContext() ;
+	    		Util.bind(ic, jndiName, this) ;
+	    	} catch (final NamingException ne) {
+	    		// Add jndi_failed to bundle
+	        	LogManager.logError(LogConstants.CTX_RUNTIME, ne, IntegrationPlugin.Util.getString("jndi_failed", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
+	    	}
+    	}
+    	
+    	// add vdb life cycle listeners
+		this.vdbRepository.addListener(new VDBLifeCycleListener() {
+
+			@Override
+			public void removed(String name, int version) {
+				
+			}
+			
+			@Override
+			public void added(String name, int version) {
+				// terminate all the previous sessions
+				try {
+					Collection<SessionMetadata> sessions = sessionService.getActiveSessions();
+					for (SessionMetadata session:sessions) {
+						if (name.equalsIgnoreCase(session.getVDBName()) && version == session.getVDBVersion()){
+							sessionService.terminateSession(session.getSessionId(), null);
+						}
+					}
+				} catch (SessionServiceException e) {
+					//ignore
+				}
+
+				// dump the caches. 
+				dqpCore.clearCache(Cache.PREPARED_PLAN_CACHE.toString(), name, version);
+				dqpCore.clearCache(Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString(), name, version);
+			}			
+		});    	
+	}	
+    
+    public void stop() {
+    	if (jndiName != null) {
+	    	final InitialContext ic ;
+	    	try {
+	    		ic = new InitialContext() ;
+	    		Util.unbind(ic, jndiName) ;
+	    	} catch (final NamingException ne) {
+	    	}
+    	}
+    	
+    	try {
+	    	this.dqpCore.stop();
+    	} catch(TeiidRuntimeException e) {
+    		// this bean is already shutdown
+    	}
+    	
+    	// Stop socket transport(s)
+    	if (this.jdbcSocket != null) {
+    		this.jdbcSocket.stop();
+    		this.jdbcSocket = null;
+    	}
+    	
+    	if (this.adminSocket != null) {
+    		this.adminSocket.stop();
+    		this.adminSocket = null;
+    	}    
+    	
+    	if (this.odbcSocket != null) {
+    		this.odbcSocket.stop();
+    		this.odbcSocket = null;
+    	}      	
+    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("engine_stopped", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
+    }
+    
+	private void createClientServices() {
+		
+		this.dqpCore.start(this);
+		
+		this.logon = new LogonImpl(this.sessionService, "teiid-cluster"); //$NON-NLS-1$
+		if (profileService != null) {
+			this.admin = AdminProvider.getLocal(profileService);
+		} else {
+			try {
+				this.admin = AdminProvider.getLocal();
+			} catch (AdminComponentException e) {
+				throw new TeiidRuntimeException(e.getCause());
+			}
+		}
+	}    
+	
+	/**
+	 * Creates an proxy to validate the incoming session
+	 */
+	private <T> T proxyService(final Class<T> iface, final T instance, String context) {
+
+		return iface.cast(Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {iface}, new LogManager.LoggingProxy(instance, context, MessageLevel.TRACE) {
+
+			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+				Throwable exception = null;
+				try {
+					sessionService.validateSession(DQPWorkContext.getWorkContext().getSessionId());
+					return super.invoke(proxy, method, args);
+				} catch (InvocationTargetException e) {
+					exception = e.getTargetException();
+				} catch(Throwable t){
+					exception = t;
+				}
+				throw ExceptionUtil.convertException(method, exception);
+			}
+		}));
+	}
+	
+	public void setJdbcSocketConfiguration(SocketConfiguration socketConfig) {
+		this.jdbcSocketConfiguration = socketConfig;
+	}
+	
+	public void setAdminSocketConfiguration(SocketConfiguration socketConfig) {
+		this.adminSocketConfiguration = socketConfig;
+	}
+	
+	public void setOdbcSocketConfiguration(SocketConfiguration socketConfig) {
+		this.odbcSocketConfiguration = socketConfig;
+	}
+    
+    public void setXATerminator(XATerminator xaTerminator){
+    	this.transactionServerImpl.setXaTerminator(xaTerminator);
+    }   
+    
+    public void setTransactionManager(TransactionManager transactionManager) {
+    	this.transactionServerImpl.setTransactionManager(transactionManager);
+    }
+    
+    public void setWorkManager(WorkManager mgr) {
+    	this.transactionServerImpl.setWorkManager(mgr);
+    }
+	
+	public void setSessionService(SessionService service) {
+		this.sessionService = service;
+		service.setDqp(this.dqpCore);
+	}
+	
+	public void setBufferService(BufferService service) {
+		this.dqpCore.setBufferService(service);
+	}
+	
+	public void setSecurityHelper(SecurityHelper helper) {
+		this.csr.setSecurityHelper(helper);
+	}
+	
+	public void setVDBRepository(VDBRepository repo) {
+		this.vdbRepository = repo;
+	}
+	
+	public void setProfileService(final ProfileService profileService) {
+		this.profileService = profileService ;
+	}
+	
+	public void setJndiName(final String jndiName) {
+		this.jndiName = jndiName ;
+	}
+	
+	@Override
+    @ManagementOperation(description="Requests for perticular session", impact=Impact.ReadOnly,params={@ManagementParameter(name="sessionId",description="The session Identifier")})
+    public List<RequestMetadata> getRequestsForSession(String sessionId) {
+		return this.dqpCore.getRequestsForSession(sessionId);
+	}
+	
+	@Override
+    @ManagementOperation(description="Requests using a certain VDB", impact=Impact.ReadOnly,params={@ManagementParameter(name="vdbName",description="VDB Name"), @ManagementParameter(name="vdbVersion",description="VDB Version")})
+    public List<RequestMetadata> getRequestsUsingVDB(String vdbName, int vdbVersion) throws AdminException {
+		List<RequestMetadata> requests = new ArrayList<RequestMetadata>();
+		try {
+			Collection<SessionMetadata> sessions = this.sessionService.getActiveSessions();
+			for (SessionMetadata session:sessions) {
+				if (session.getVDBName().equals(vdbName) && session.getVDBVersion() == vdbVersion) {
+					requests.addAll(this.dqpCore.getRequestsForSession(session.getSessionId()));
+				}
+			}
+		} catch (SessionServiceException e) {
+			throw new AdminComponentException(e);
+		}
+		return requests;
+	}
+	
+    
+	@Override
+    @ManagementOperation(description="Active requests", impact=Impact.ReadOnly)
+    public List<RequestMetadata> getRequests() {
+		return this.dqpCore.getRequests();
+	}
+	
+	@Override
+    @ManagementOperation(description="Long running requests", impact=Impact.ReadOnly)
+    public List<RequestMetadata> getLongRunningRequests() {
+		return this.dqpCore.getLongRunningRequests();
+	}
+	
+	
+	@Override
+	@ManagementOperation(description="Get thread statistics worker pool", impact=Impact.ReadOnly,params={@ManagementParameter(name="identifier",description="Get thread statistics worker pool")})
+    public WorkerPoolStatisticsMetadata getWorkerPoolStatistics(){
+		return this.dqpCore.getWorkerPoolStatistics();
+	}
+	
+	@Override
+    @ManagementOperation(description="Terminate a Session",params={@ManagementParameter(name="terminateeId",description="The session to be terminated")})
+    public void terminateSession(String terminateeId) {
+		this.sessionService.terminateSession(terminateeId, DQPWorkContext.getWorkContext().getSessionId());
+    }
+    
+	@Override
+    @ManagementOperation(description="Cancel a Request",params={@ManagementParameter(name="sessionId",description="The session Identifier"), @ManagementParameter(name="executionId",description="The Execution Identifier")})    
+    public boolean cancelRequest(String sessionId, long executionId) throws AdminException {
+    	try {
+			return this.dqpCore.cancelRequest(sessionId, executionId);
+		} catch (TeiidComponentException e) {
+			throw new AdminComponentException(e);
+		}
+    }
+    
+	@Override
+    @ManagementOperation(description="Get Cache types in the system", impact=Impact.ReadOnly)
+    public Collection<String> getCacheTypes(){
+		return this.dqpCore.getCacheTypes();
+	}
+	
+	@Override
+	@ManagementOperation(description="Clear the caches in the system", impact=Impact.ReadOnly)
+	public void clearCache(String cacheType) {
+		this.dqpCore.clearCache(cacheType);
+	}
+	
+	@Override
+	@ManagementOperation(description="Get the cache statistics", impact=Impact.ReadOnly)
+	public CacheStatisticsMetadata getCacheStatistics(String cacheType) {
+		return this.dqpCore.getCacheStatistics(cacheType);
+	}
+	
+	@Override
+	@ManagementOperation(description="Active sessions", impact=Impact.ReadOnly)
+	public Collection<SessionMetadata> getActiveSessions() throws AdminException {
+		try {
+			return this.sessionService.getActiveSessions();
+		} catch (SessionServiceException e) {
+			throw new AdminComponentException(e);
+		}
+	}
+	
+	@Override
+	@ManagementProperty(description="Active session count", use={ViewUse.STATISTIC}, readOnly=true)
+	public int getActiveSessionsCount() throws AdminException{
+		try {
+			return this.sessionService.getActiveSessionsCount();
+		} catch (SessionServiceException e) {
+			throw new AdminComponentException(e);
+		}
+	}
+	
+	@Override
+	@ManagementOperation(description="Active Transactions", impact=Impact.ReadOnly)
+	public Collection<org.teiid.adminapi.Transaction> getTransactions() {
+		return this.dqpCore.getTransactions();
+	}
+	
+	@Override
+	@ManagementOperation(description="Terminate the transaction", impact=Impact.ReadOnly)
+	public void terminateTransaction(String xid) throws AdminException {
+		this.dqpCore.terminateTransaction(xid);
+	}
+
+	@Override
+    @ManagementOperation(description="Merge Two VDBs",params={@ManagementParameter(name="sourceVDBName"), at ManagementParameter(name="sourceVDBName"), @ManagementParameter(name="targetVDBName"), @ManagementParameter(name="targetVDBVersion")})
+	public void mergeVDBs(String sourceVDBName, int sourceVDBVersion,
+			String targetVDBName, int targetVDBVersion) throws AdminException {
+		this.vdbRepository.mergeVDBs(sourceVDBName, sourceVDBVersion, targetVDBName, targetVDBVersion);
+	}	
+	
+	public void setCacheFactory(CacheFactory factory) {
+		this.dqpCore.setCacheFactory(factory);
+	}
+	
+	@Override
+    @ManagementOperation(description="Execute a sql query", params={@ManagementParameter(name="vdbName"), at ManagementParameter(name="vdbVersion"), @ManagementParameter(name="command"), @ManagementParameter(name="timoutInMilli")})	
+	public List<List> executeQuery(final String vdbName, final int version, final String command, final long timoutInMilli) throws AdminException {
+		Properties properties = new Properties();
+		properties.setProperty(TeiidURL.JDBC.VDB_NAME, vdbName);
+		properties.setProperty(TeiidURL.JDBC.VDB_VERSION, String.valueOf(version));
+		
+		String user = "JOPR ADMIN"; //$NON-NLS-1$
+		LogManager.logDetail(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("admin_executing", user, command)); //$NON-NLS-1$
+		
+		SessionMetadata session = null;
+		try {
+			session = this.sessionService.createSession(user, null, "JOPR", properties, false, false); //$NON-NLS-1$
+		} catch (SessionServiceException e1) {
+			throw new AdminProcessingException(e1);
+		} catch (LoginException e1) {
+			throw new AdminProcessingException(e1);
+		}
+
+		final long requestID =  0L;
+		
+		DQPWorkContext context = new DQPWorkContext();
+		context.setSession(session);
+		
+		try {
+			return context.runInContext(new Callable<List<List>>() {
+				@Override
+				public List<List> call() throws Exception {
+					ArrayList<List> results = new ArrayList<List>();
+					
+					long start = System.currentTimeMillis();
+					RequestMessage request = new RequestMessage(command);
+					request.setExecutionId(0L);
+					request.setRowLimit(getMaxRowsFetchSize()); // this would limit the number of rows that are returned.
+					Future<ResultsMessage> message = dqpCore.executeRequest(requestID, request);
+					ResultsMessage rm = message.get(timoutInMilli, TimeUnit.MILLISECONDS);
+					
+			        if (rm.getException() != null) {
+			            throw new AdminProcessingException(rm.getException());
+			        }
+			        
+			        if (rm.isUpdateResult()) {
+			        	results.addAll(new ArrayList(Arrays.asList("update count"))); //$NON-NLS-1$
+			        	results.addAll(Arrays.asList(rm.getResults()));			        	
+			        }
+			        else {
+				        results.addAll(new ArrayList(Arrays.asList(rm.getColumnNames())));
+				        results.addAll(Arrays.asList(fixResults(rm.getResults())));
+				        
+				        while (rm.getFinalRow() == -1 || rm.getLastRow() < rm.getFinalRow()) {
+				        	long elapsed = System.currentTimeMillis() - start;
+							message = dqpCore.processCursorRequest(requestID, rm.getLastRow()+1, 1024);
+							rm = message.get(timoutInMilli-elapsed, TimeUnit.MILLISECONDS);
+							results.addAll(Arrays.asList(fixResults(rm.getResults())));
+				        }
+			        }
+
+			        long elapsed = System.currentTimeMillis() - start;
+			        ResultsFuture<?> response = dqpCore.closeRequest(requestID);
+			        response.get(timoutInMilli-elapsed, TimeUnit.MILLISECONDS);
+					return results;
+				}
+			});
+		} catch (Throwable t) {
+			throw new AdminProcessingException(t);
+		} finally {
+			try {
+				sessionService.closeSession(session.getSessionId());
+			} catch (InvalidSessionException e) { //ignore
+			}			
+		}
+	}	
+	
+	/**
+	 * Managed Object framework has bug that does not currently allow 
+	 * sending a NULL in the Collection Value, so sending literal string "null". 
+	 * If you send them as Array Value, the MO is packaged as composite object and would like 
+	 * all the elements in array to be same type which is not the case with results. 
+	 */
+	List[] fixResults(List[] rows) throws SQLException {
+		List[] newResults = new List[rows.length];
+		
+		for(int i = 0; i < rows.length; i++) {
+			List row = rows[i];
+			ArrayList newRow = new ArrayList();
+			for (Object col:row) {
+				if (col == null) {
+					newRow.add("null"); //$NON-NLS-1$ 
+				}
+				else {
+					if (col instanceof Number || col instanceof String || col instanceof Character) {
+						newRow.add(col);
+					}
+					else if (col instanceof Blob) {
+						newRow.add("blob"); //$NON-NLS-1$
+					}
+					else if (col instanceof Clob) {
+						newRow.add("clob"); //$NON-NLS-1$
+					}
+					else if (col instanceof SQLXML) {
+						SQLXML xml = (SQLXML)col;
+						newRow.add(xml.getString());
+					}
+					else {
+						newRow.add(col.toString());
+					}
+				}
+			}
+			newResults[i] = newRow;
+		}		
+		return newResults;
+	}
+}

Deleted: tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties
===================================================================
--- branches/7.2.x/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,48 +0,0 @@
-#
-# JBoss, Home of Professional Open Source.
-# See the COPYRIGHT.txt file distributed with this work for information
-# regarding copyright ownership.  Some portions may be licensed
-# to Red Hat, Inc. under one or more contributor license agreements.
-# 
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-# 
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-# Lesser General Public License for more details.
-# 
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-# 02110-1301 USA.
-#
-
-engine_started=Teiid Engine Started = {0}
-socket_enabled={0} {1}
-odbc_not_enabled=ODBC transport is not enabled in Teiid.
-odbc_enabled={0} {1}
-engine_stopped=Teiid Engine stopped {0}
-admin_connection_closed=Teiid admin connection is already closed.
-bad_vdb_extension=The extension of the file name must be either ".vdb" for designer vdb or "xxx-vdb.xml" for dynamic VDBs
-vdb_not_found=VDB with name "{0}" version "{1}" not found in configuration
-model_not_found=Model name "{0}" not found in the VDB with name "{1}" version "{2}"
-policy_not_found=Policy name "{0}" not found in the VDB with name "{1}" version "{2}"
-datasource_not_found=Datasource {0} not found in the configuration.
-sourcename_not_found=No source name {0} found in the model: {1}.{2}.{3}
-
-no_operation=No operation found with given name = {0}
-failed_to_remove=Failed to remove the deployment
-deployment_start_failed={0} deployment start failed
-failed_to_convert=Failed to convert from String value to {0} type
-property_required_not_found="{0}" is required for the connector type "{1}", but was not supplied; There is no default value either.
-invalid_class={0} invalid type of class specified. Must be of type org.teiid.connector.api.ConnectorEnvironment
-class_not_found=Class {0} not found.
-datasource_exists=Data source with name {0} already exists!
-datasource_template_not_found=Template {0} for creating the data source is not found.
-jndi_failed=JNDI lookup failed.
-distribute_failed=Deploy of the archive failed {0}
-template_not_found=Template not found for {0}
-admin_executing=JOPR admin {0} is executing command {1}

Copied: tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties (from rev 2707, branches/7.2.x/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties)
===================================================================
--- tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,48 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership.  Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+# 
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+# 
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
+# 
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
+
+engine_started=Teiid Engine {0} Started = {1}
+socket_enabled={0} {1}
+odbc_not_enabled=ODBC transport is not enabled in Teiid.
+odbc_enabled={0} {1}
+engine_stopped=Teiid Engine stopped {0}
+admin_connection_closed=Teiid admin connection is already closed.
+bad_vdb_extension=The extension of the file name must be either ".vdb" for designer vdb or "xxx-vdb.xml" for dynamic VDBs
+vdb_not_found=VDB with name "{0}" version "{1}" not found in configuration
+model_not_found=Model name "{0}" not found in the VDB with name "{1}" version "{2}"
+policy_not_found=Policy name "{0}" not found in the VDB with name "{1}" version "{2}"
+datasource_not_found=Datasource {0} not found in the configuration.
+sourcename_not_found=No source name {0} found in the model: {1}.{2}.{3}
+
+no_operation=No operation found with given name = {0}
+failed_to_remove=Failed to remove the deployment
+deployment_start_failed={0} deployment start failed
+failed_to_convert=Failed to convert from String value to {0} type
+property_required_not_found="{0}" is required for the connector type "{1}", but was not supplied; There is no default value either.
+invalid_class={0} invalid type of class specified. Must be of type org.teiid.connector.api.ConnectorEnvironment
+class_not_found=Class {0} not found.
+datasource_exists=Data source with name {0} already exists!
+datasource_template_not_found=Template {0} for creating the data source is not found.
+jndi_failed=JNDI lookup failed.
+distribute_failed=Deploy of the archive failed {0}
+template_not_found=Template not found for {0}
+admin_executing=JOPR admin {0} is executing command {1}

Deleted: tags/teiid-parent-7.2.0.Final/metadata/pom.xml
===================================================================
--- branches/7.2.x/metadata/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/metadata/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,69 +0,0 @@
-<?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">
-  <parent>
-    <artifactId>teiid-parent</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>teiid-metadata</artifactId>
-  <name>Metadata</name>
-  <description>Provides vdb metadata from index files.</description>
-  
-  <dependencies>
-
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <scope>provided</scope>
-    </dependency>    
-
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <type>test-jar</type>
-    </dependency>    
-        
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-engine</artifactId>
-    </dependency>
-    
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-engine</artifactId>
-      <type>test-jar</type>
-    </dependency>
-           
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-client</artifactId>
-      <scope>provided</scope>
-    </dependency>
-    
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-api</artifactId>
-      <scope>provided</scope>
-    </dependency>
-        
-    <dependency>
-      <groupId>javax.resource</groupId>
-      <artifactId>connector-api</artifactId>
-      <scope>provided</scope>
-    </dependency>
-    
-    <dependency>
-        <groupId>org.jboss</groupId>
-        <artifactId>jboss-vfs</artifactId>
-        <scope>provided</scope>
-    </dependency>
-
-	<dependency>
-		<groupId>org.jboss.man</groupId>
-		<artifactId>jboss-managed</artifactId>
-	</dependency>
-  
-  </dependencies>
-  
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/metadata/pom.xml (from rev 2708, branches/7.2.x/metadata/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/metadata/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/metadata/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,69 @@
+<?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">
+  <parent>
+    <artifactId>teiid-parent</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>teiid-metadata</artifactId>
+  <name>Metadata</name>
+  <description>Provides vdb metadata from index files.</description>
+  
+  <dependencies>
+
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <scope>provided</scope>
+    </dependency>    
+
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <type>test-jar</type>
+    </dependency>    
+        
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-engine</artifactId>
+    </dependency>
+    
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-engine</artifactId>
+      <type>test-jar</type>
+    </dependency>
+           
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-client</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-api</artifactId>
+      <scope>provided</scope>
+    </dependency>
+        
+    <dependency>
+      <groupId>javax.resource</groupId>
+      <artifactId>connector-api</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    
+    <dependency>
+        <groupId>org.jboss</groupId>
+        <artifactId>jboss-vfs</artifactId>
+        <scope>provided</scope>
+    </dependency>
+
+	<dependency>
+		<groupId>org.jboss.man</groupId>
+		<artifactId>jboss-managed</artifactId>
+	</dependency>
+  
+  </dependencies>
+  
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/pom.xml
===================================================================
--- branches/7.2.x/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,493 +0,0 @@
-<?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>
-	<groupId>org.jboss.teiid</groupId>
-	<artifactId>teiid-parent</artifactId>
-	<packaging>pom</packaging>
-	<name>Teiid</name>
-	<version>7.2.0.Final-SNAPSHOT</version>
-	<description>Federated SQL and XML query engine.</description>
-	<properties>
-		<ant.version>1.7.0</ant.version>
-		<site.url>http://www.jboss.org/teiid</site.url>
-	</properties>
-	<scm>
-        <connection>scm:svn:https://anonsvn.jboss.org/repos/teiid/trunk</connection>
-		<developerConnection>scm:svn:https://svn.jboss.org/repos/teiid/trunk</developerConnection>
-	</scm>
-	<licenses>
-		<license>
-			<name>GNU Lesser General Public License</name>
-			<url>http://www.gnu.org/licenses/lgpl.html</url>
-			<distribution>repo</distribution>
-			<comments>A business-friendly OSS license</comments>
-		</license>
-	</licenses>
-	<url>${site.url}</url>
-	<developers>
-		<developer>
-			<name>Steve Hawkins</name>
-			<id>steve</id>
-			<email>shawkins at redhat.com</email>
-			<organization>Red Hat</organization>
-			<roles>
-				<role>Project Lead</role>
-			</roles>
-			<timezone>-6</timezone>
-		</developer>
-		<developer>
-			<name>Ramesh Reddy</name>
-			<id>ramesh</id>
-			<email>rareddy at redhat.com</email>
-			<organization>Red Hat</organization>
-			<roles>
-				<role>Project Lead</role>
-			</roles>
-			<timezone>-6</timezone>
-		</developer>
-		<developer>
-			<name>Van Halbert</name>
-			<id>van</id>
-			<email>vhalbert at redhat.com</email>
-			<organization>Red Hat</organization>
-			<roles>
-				<role>Developer</role>
-			</roles>
-			<timezone>-6</timezone>
-		</developer>
-		<developer>
-			<name>Ted Jones</name>
-			<id>ted</id>
-			<email>tejones at redhat.com</email>
-			<organization>Red Hat</organization>
-			<roles>
-				<role>Developer</role>
-			</roles>
-			<timezone>-6</timezone>
-		</developer>
-	</developers>
-	<profiles>
-    <profile>
-      <!-- 
-          This profile is activated manually, as in "mvn ... -P release ..."
-		  -->
-      <id>release</id>
-      <modules>
-        <module>documentation</module>
-        <module>build</module>        
-      </modules>
-    </profile>
-    <profile>
-      <!--
-          This is to enable faster build for development time.
-          -->
-      <id>dev</id>
-      <modules>
-        <module>build</module>
-      </modules>
-    </profile>
-	</profiles>
-	<build>
-	<!-- This section defines the default plugin settings inherited by child projects. -->
-		<pluginManagement>
-			<plugins>
-		<!-- Fixes how test resources of a project can be used in projects dependent on it  -->
-				<plugin>
-					<groupId>org.apache.maven.plugins</groupId>
-					<artifactId>maven-jar-plugin</artifactId>
-					<version>2.2</version>
-				</plugin>
-				<plugin>
-				  <artifactId>maven-assembly-plugin</artifactId>
-				  <version>2.2-beta-6-m1-jboss</version>
-				</plugin>
-			</plugins>
-		</pluginManagement>
-		<plugins>
-	  <!-- Specify the compiler options and settings -->
-			<plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-compiler-plugin</artifactId>
-				<configuration>
-					<source>1.6</source>
-					<target>1.6</target>
-					<showDeprecation>false</showDeprecation>
-					<showWarnings>false</showWarnings>
-				</configuration>
-			</plugin>
-			<plugin>
-				<artifactId>maven-surefire-plugin</artifactId>
-				<configuration>
-					<includes>
-						<include>**/*TestCase.java</include>
-						<include>**/*Test.java</include>
-						<include>**/Test*.java</include>
-					</includes>
-					<excludes>
-						<exclude>**/Abstract*TestCase.java</exclude>
-			<!-- hack to prevent anonymous inner classes in Tests from being run as tests -->
-						<include>**/Test*$*.java</include>
-					</excludes>
-					<systemProperties>
-						<property>
-							<name>user.dir</name>
-							<value>${basedir}/target</value>
-						</property>
-						<property>
-							<name>java.io.tmpdir</name>
-							<value>${basedir}/target</value>
-						</property>
-					</systemProperties>
-				</configuration>
-			</plugin>
-      <!-- 
-      Build a test-jar for each project, so that src/test/* resources and classes can be used
-      in other projects.  Also customize how the jar files are assembled.
-      -->
-			<plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-jar-plugin</artifactId>
-				<executions>
-					<execution>
-						<goals>
-							<goal>test-jar</goal>
-						</goals>
-					</execution>
-				</executions>
-				<configuration>
-					<archive>
-						<manifest>
-							<addDefaultSpecificationEntries> true</addDefaultSpecificationEntries>
-							<addDefaultImplementationEntries> true</addDefaultImplementationEntries>
-						</manifest>
-						<manifestEntries>
-							<Implementation-URL>${pom.url}</Implementation-URL>
-						</manifestEntries>
-					</archive>
-				</configuration>
-			</plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-source-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>attach-sources</id>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                    </execution>
-                </executions>
-            </plugin>
-			<plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-javadoc-plugin</artifactId>
-				<version>2.5</version>
-			</plugin>            
-		</plugins>
-	</build>
-	<reporting>
-		<plugins>
-			<plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-javadoc-plugin</artifactId>
-				<configuration>
-					<aggregate>true</aggregate>
-					<maxmemory>512m</maxmemory>
-					<excludePackageNames>*.internal</excludePackageNames>
-				</configuration>
-			</plugin>
-		</plugins>
-	</reporting>
-	<repositories>
-		<repository>
-			<id>jboss-public-repository</id>
-            <name>JBoss Public Maven Repository Group</name>
-			<url>http://repository.jboss.org/nexus/content/groups/public/</url>
-		</repository>
-	</repositories>
-	<dependencies>
-		<dependency>
-			<groupId>junit</groupId>
-			<artifactId>junit</artifactId>
-			<version>4.4</version>
-			<scope>test</scope>
-		</dependency>
-		<dependency>
-			<groupId>org.mockito</groupId>
-			<artifactId>mockito-all</artifactId>
-			<version>1.5</version>
-			<scope>test</scope>
-		</dependency>
-	</dependencies>
-	<dependencyManagement>
-		<dependencies>
-      <!--
-      Declare all dependency versions and default scopes here, but not optional.
-      Each module should declare it's direct dependency and possibily overwrite scope/optional.
-      -->
-      
-      <!-- Internal dependencies -->
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-common-core</artifactId>
-				<version>${project.version}</version>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-common-core</artifactId>
-				<type>test-jar</type>
-				<version>${project.version}</version>
-				<scope>test</scope>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-api</artifactId>
-				<version>${project.version}</version>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-api</artifactId>
-				<type>test-jar</type>
-				<version>${project.version}</version>
-				<scope>test</scope>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-console</artifactId>
-				<version>${project.version}</version>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-console</artifactId>
-				<type>test-jar</type>
-				<version>${project.version}</version>
-				<scope>test</scope>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-client</artifactId>
-				<version>${project.version}</version>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-client</artifactId>
-				<type>test-jar</type>
-				<version>${project.version}</version>
-				<scope>test</scope>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-engine</artifactId>
-				<version>${project.version}</version>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-engine</artifactId>
-				<type>test-jar</type>
-				<version>${project.version}</version>
-				<scope>test</scope>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-metadata</artifactId>
-				<version>${project.version}</version>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-metadata</artifactId>
-				<type>test-jar</type>
-				<version>${project.version}</version>
-				<scope>test</scope>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-txn-jbossts</artifactId>
-				<version>${project.version}</version>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.teiid</groupId>
-				<artifactId>teiid-cache-jbosscache</artifactId>
-				<version>${project.version}</version>
-			</dependency>
-            <dependency>
-                <groupId>org.jboss.teiid</groupId>
-                <artifactId>teiid-jboss-integration</artifactId>
-                <version>${project.version}</version>
-            </dependency>
-            <dependency>
-                <groupId>org.jboss.teiid</groupId>
-                <artifactId>teiid-runtime</artifactId>
-                <version>${project.version}</version>
-            </dependency>    
-      
-      <!-- External dependencies -->
-			<dependency>
-				<groupId>javax.resource</groupId>
-				<artifactId>connector-api</artifactId>
-				<version>1.5</version>
-				<scope>provided</scope>
-			</dependency>
-			<dependency>
-				<groupId>javax.transaction</groupId>
-                <artifactId>jta</artifactId>
-				<version>1.1</version>
-				<scope>provided</scope>
-			</dependency>
-			<dependency>
-				<groupId>log4j</groupId>
-				<artifactId>log4j</artifactId>
-				<version>1.2.14</version>
-			</dependency>
-			<dependency>
-				<groupId>commons-logging</groupId>
-				<artifactId>commons-logging</artifactId>
-				<version>1.1</version>
-				<exclusions>
-					<exclusion>
-						<groupId>logkit</groupId>
-						<artifactId>logkit</artifactId>
-					</exclusion>
-					<exclusion>
-						<groupId>avalon-framework</groupId>
-						<artifactId>avalon-framework</artifactId>
-					</exclusion>
-                    <exclusion>
-                        <groupId>javax.servlet</groupId>
-                        <artifactId>servlet-api</artifactId>
-                    </exclusion>       
-				</exclusions>
-			</dependency>
-			<dependency>
-				<groupId>jgroups</groupId>
-				<artifactId>jgroups</artifactId>
-				<version>2.6.10.GA</version>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.cache</groupId>
-				<artifactId>jbosscache-core</artifactId>
-				<version>3.1.0.GA</version>
-                <exclusions>
-                    <exclusion>
-                      <groupId>javax.transaction</groupId>
-                      <artifactId>jta</artifactId>
-                    </exclusion>
-                    <exclusion>
-                        <groupId>commons-logging</groupId>
-                        <artifactId>commons-logging</artifactId>
-                    </exclusion>       
-                    <exclusion>
-                        <groupId>org.jboss</groupId>
-                        <artifactId>jboss-common-core</artifactId>
-                    </exclusion>                          
-                </exclusions>                
-			</dependency>
-            <dependency>
-                <groupId>org.jboss.man</groupId>
-                <artifactId>jboss-managed</artifactId>
-                <version>2.1.0.SP1</version>
-                <scope>provided</scope>
-            </dependency>        
-            <dependency>
-              <groupId>org.jboss.man</groupId>
-              <artifactId>jboss-metatype</artifactId>
-              <version>2.1.0.SP1</version>
-              <scope>provided</scope>
-            </dependency>            
-            <dependency>
-                <groupId>org.jboss.integration</groupId>
-                <artifactId>jboss-profileservice-spi</artifactId>
-                <version>5.1.0.GA</version>
-                <scope>provided</scope>
-            </dependency>      
-            <dependency>    
-                <groupId>org.jboss</groupId>
-                <artifactId>jboss-vfs</artifactId>
-                <version>2.1.2.GA</version>
-                <scope>provided</scope>
-            </dependency>
-            <dependency>    
-                <groupId>org.jboss.deployers</groupId>
-                <artifactId>jboss-deployers-vfs-spi</artifactId>
-                <version>2.0.7.GA</version>
-                <scope>provided</scope>
-            </dependency>      
-            <dependency>    
-                <groupId>org.jboss.deployers</groupId>
-                <artifactId>jboss-deployers-vfs</artifactId>
-                <version>2.0.7.GA</version>
-                <scope>provided</scope>
-            </dependency>              
-            <dependency>
-              <groupId>org.jboss.jbossas</groupId>
-              <artifactId>jboss-as-connector</artifactId>
-              <version>5.1.0.GA</version>
-              <scope>provided</scope>
-            </dependency>
-            <dependency>
-                <groupId>org.jboss</groupId>
-                <artifactId>jboss-reflect</artifactId>
-                <version>2.0.2.GA</version>
-                <scope>provided</scope>
-            </dependency>             
-            <dependency>
-              <groupId>org.jboss.remoting</groupId>
-              <artifactId>jboss-remoting</artifactId>
-              <version>2.5.1</version>
-              <scope>provided</scope>
-            </dependency>            
-			<dependency>
-				<groupId>net.sourceforge.saxon</groupId>
-				<artifactId>saxon</artifactId>
-				<version>9.1.0.8</version>
-			</dependency>
-			<dependency>
-				<groupId>net.sourceforge.saxon</groupId>
-				<artifactId>saxon</artifactId>
-				<classifier>dom</classifier>
-				<version>9.1.0.8</version>
-			</dependency>
-			<dependency>
-				<groupId>org.jboss.netty</groupId>
-				<artifactId>netty</artifactId>
-				<version>3.2.1.Final</version>
-			</dependency>
-			<dependency>
-				<groupId>org.apache.ant</groupId>
-				<artifactId>ant</artifactId>
-				<version>${ant.version}</version>
-			</dependency>
-			<dependency>
-  				<groupId>com.googlecode.json-simple</groupId>
-				<artifactId>json-simple</artifactId>
-  				<version>1.1</version>
-			</dependency>
-		</dependencies>
-	</dependencyManagement>
-	<modules>
-		<module>common-core</module>
-		<module>api</module>
-		<module>client</module>
-		<module>engine</module>
-		<module>connectors</module>
-		<module>console</module>
-		<module>metadata</module>
-		<module>runtime</module>
-		<module>adminshell</module>
-		<module>cache-jbosscache</module>
-		<module>hibernate-dialect</module>
-        <module>jboss-integration</module>
-		<module>test-integration</module>
-  </modules>
-    <distributionManagement>
-        <repository>
-            <id>jboss-releases-repository</id>
-            <name>JBoss Releases Repository</name>
-            <url>https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/</url>
-        </repository>
-        <snapshotRepository>
-            <id>jboss-snapshots-repository</id>
-            <name>JBoss Snapshots Repository</name>
-            <url>https://repository.jboss.org/nexus/content/repositories/snapshots/</url>
-        </snapshotRepository>
-    </distributionManagement>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/pom.xml (from rev 2708, branches/7.2.x/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,493 @@
+<?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>
+	<groupId>org.jboss.teiid</groupId>
+	<artifactId>teiid-parent</artifactId>
+	<packaging>pom</packaging>
+	<name>Teiid</name>
+	<version>7.2.0.Final</version>
+	<description>Federated SQL and XML query engine.</description>
+	<properties>
+		<ant.version>1.7.0</ant.version>
+		<site.url>http://www.jboss.org/teiid</site.url>
+	</properties>
+	<scm>
+        <connection>scm:svn:https://anonsvn.jboss.org/repos/teiid/tags/teiid-parent-7.2.0.Final</connection>
+		<developerConnection>scm:svn:https://svn.jboss.org/repos/teiid/tags/teiid-parent-7.2.0.Final</developerConnection>
+	</scm>
+	<licenses>
+		<license>
+			<name>GNU Lesser General Public License</name>
+			<url>http://www.gnu.org/licenses/lgpl.html</url>
+			<distribution>repo</distribution>
+			<comments>A business-friendly OSS license</comments>
+		</license>
+	</licenses>
+	<url>${site.url}</url>
+	<developers>
+		<developer>
+			<name>Steve Hawkins</name>
+			<id>steve</id>
+			<email>shawkins at redhat.com</email>
+			<organization>Red Hat</organization>
+			<roles>
+				<role>Project Lead</role>
+			</roles>
+			<timezone>-6</timezone>
+		</developer>
+		<developer>
+			<name>Ramesh Reddy</name>
+			<id>ramesh</id>
+			<email>rareddy at redhat.com</email>
+			<organization>Red Hat</organization>
+			<roles>
+				<role>Project Lead</role>
+			</roles>
+			<timezone>-6</timezone>
+		</developer>
+		<developer>
+			<name>Van Halbert</name>
+			<id>van</id>
+			<email>vhalbert at redhat.com</email>
+			<organization>Red Hat</organization>
+			<roles>
+				<role>Developer</role>
+			</roles>
+			<timezone>-6</timezone>
+		</developer>
+		<developer>
+			<name>Ted Jones</name>
+			<id>ted</id>
+			<email>tejones at redhat.com</email>
+			<organization>Red Hat</organization>
+			<roles>
+				<role>Developer</role>
+			</roles>
+			<timezone>-6</timezone>
+		</developer>
+	</developers>
+	<profiles>
+    <profile>
+      <!-- 
+          This profile is activated manually, as in "mvn ... -P release ..."
+		  -->
+      <id>release</id>
+      <modules>
+        <module>documentation</module>
+        <module>build</module>        
+      </modules>
+    </profile>
+    <profile>
+      <!--
+          This is to enable faster build for development time.
+          -->
+      <id>dev</id>
+      <modules>
+        <module>build</module>
+      </modules>
+    </profile>
+	</profiles>
+	<build>
+	<!-- This section defines the default plugin settings inherited by child projects. -->
+		<pluginManagement>
+			<plugins>
+		<!-- Fixes how test resources of a project can be used in projects dependent on it  -->
+				<plugin>
+					<groupId>org.apache.maven.plugins</groupId>
+					<artifactId>maven-jar-plugin</artifactId>
+					<version>2.2</version>
+				</plugin>
+				<plugin>
+				  <artifactId>maven-assembly-plugin</artifactId>
+				  <version>2.2-beta-6-m1-jboss</version>
+				</plugin>
+			</plugins>
+		</pluginManagement>
+		<plugins>
+	  <!-- Specify the compiler options and settings -->
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-compiler-plugin</artifactId>
+				<configuration>
+					<source>1.6</source>
+					<target>1.6</target>
+					<showDeprecation>false</showDeprecation>
+					<showWarnings>false</showWarnings>
+				</configuration>
+			</plugin>
+			<plugin>
+				<artifactId>maven-surefire-plugin</artifactId>
+				<configuration>
+					<includes>
+						<include>**/*TestCase.java</include>
+						<include>**/*Test.java</include>
+						<include>**/Test*.java</include>
+					</includes>
+					<excludes>
+						<exclude>**/Abstract*TestCase.java</exclude>
+			<!-- hack to prevent anonymous inner classes in Tests from being run as tests -->
+						<include>**/Test*$*.java</include>
+					</excludes>
+					<systemProperties>
+						<property>
+							<name>user.dir</name>
+							<value>${basedir}/target</value>
+						</property>
+						<property>
+							<name>java.io.tmpdir</name>
+							<value>${basedir}/target</value>
+						</property>
+					</systemProperties>
+				</configuration>
+			</plugin>
+      <!-- 
+      Build a test-jar for each project, so that src/test/* resources and classes can be used
+      in other projects.  Also customize how the jar files are assembled.
+      -->
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-jar-plugin</artifactId>
+				<executions>
+					<execution>
+						<goals>
+							<goal>test-jar</goal>
+						</goals>
+					</execution>
+				</executions>
+				<configuration>
+					<archive>
+						<manifest>
+							<addDefaultSpecificationEntries> true</addDefaultSpecificationEntries>
+							<addDefaultImplementationEntries> true</addDefaultImplementationEntries>
+						</manifest>
+						<manifestEntries>
+							<Implementation-URL>${pom.url}</Implementation-URL>
+						</manifestEntries>
+					</archive>
+				</configuration>
+			</plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-source-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>attach-sources</id>
+                        <goals>
+                            <goal>jar</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-javadoc-plugin</artifactId>
+				<version>2.5</version>
+			</plugin>            
+		</plugins>
+	</build>
+	<reporting>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-javadoc-plugin</artifactId>
+				<configuration>
+					<aggregate>true</aggregate>
+					<maxmemory>512m</maxmemory>
+					<excludePackageNames>*.internal</excludePackageNames>
+				</configuration>
+			</plugin>
+		</plugins>
+	</reporting>
+	<repositories>
+		<repository>
+			<id>jboss-public-repository</id>
+            <name>JBoss Public Maven Repository Group</name>
+			<url>http://repository.jboss.org/nexus/content/groups/public/</url>
+		</repository>
+	</repositories>
+	<dependencies>
+		<dependency>
+			<groupId>junit</groupId>
+			<artifactId>junit</artifactId>
+			<version>4.4</version>
+			<scope>test</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.mockito</groupId>
+			<artifactId>mockito-all</artifactId>
+			<version>1.5</version>
+			<scope>test</scope>
+		</dependency>
+	</dependencies>
+	<dependencyManagement>
+		<dependencies>
+      <!--
+      Declare all dependency versions and default scopes here, but not optional.
+      Each module should declare it's direct dependency and possibily overwrite scope/optional.
+      -->
+      
+      <!-- Internal dependencies -->
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-common-core</artifactId>
+				<version>${project.version}</version>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-common-core</artifactId>
+				<type>test-jar</type>
+				<version>${project.version}</version>
+				<scope>test</scope>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-api</artifactId>
+				<version>${project.version}</version>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-api</artifactId>
+				<type>test-jar</type>
+				<version>${project.version}</version>
+				<scope>test</scope>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-console</artifactId>
+				<version>${project.version}</version>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-console</artifactId>
+				<type>test-jar</type>
+				<version>${project.version}</version>
+				<scope>test</scope>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-client</artifactId>
+				<version>${project.version}</version>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-client</artifactId>
+				<type>test-jar</type>
+				<version>${project.version}</version>
+				<scope>test</scope>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-engine</artifactId>
+				<version>${project.version}</version>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-engine</artifactId>
+				<type>test-jar</type>
+				<version>${project.version}</version>
+				<scope>test</scope>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-metadata</artifactId>
+				<version>${project.version}</version>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-metadata</artifactId>
+				<type>test-jar</type>
+				<version>${project.version}</version>
+				<scope>test</scope>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-txn-jbossts</artifactId>
+				<version>${project.version}</version>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.teiid</groupId>
+				<artifactId>teiid-cache-jbosscache</artifactId>
+				<version>${project.version}</version>
+			</dependency>
+            <dependency>
+                <groupId>org.jboss.teiid</groupId>
+                <artifactId>teiid-jboss-integration</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.jboss.teiid</groupId>
+                <artifactId>teiid-runtime</artifactId>
+                <version>${project.version}</version>
+            </dependency>    
+      
+      <!-- External dependencies -->
+			<dependency>
+				<groupId>javax.resource</groupId>
+				<artifactId>connector-api</artifactId>
+				<version>1.5</version>
+				<scope>provided</scope>
+			</dependency>
+			<dependency>
+				<groupId>javax.transaction</groupId>
+                <artifactId>jta</artifactId>
+				<version>1.1</version>
+				<scope>provided</scope>
+			</dependency>
+			<dependency>
+				<groupId>log4j</groupId>
+				<artifactId>log4j</artifactId>
+				<version>1.2.14</version>
+			</dependency>
+			<dependency>
+				<groupId>commons-logging</groupId>
+				<artifactId>commons-logging</artifactId>
+				<version>1.1</version>
+				<exclusions>
+					<exclusion>
+						<groupId>logkit</groupId>
+						<artifactId>logkit</artifactId>
+					</exclusion>
+					<exclusion>
+						<groupId>avalon-framework</groupId>
+						<artifactId>avalon-framework</artifactId>
+					</exclusion>
+                    <exclusion>
+                        <groupId>javax.servlet</groupId>
+                        <artifactId>servlet-api</artifactId>
+                    </exclusion>       
+				</exclusions>
+			</dependency>
+			<dependency>
+				<groupId>jgroups</groupId>
+				<artifactId>jgroups</artifactId>
+				<version>2.6.10.GA</version>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.cache</groupId>
+				<artifactId>jbosscache-core</artifactId>
+				<version>3.1.0.GA</version>
+                <exclusions>
+                    <exclusion>
+                      <groupId>javax.transaction</groupId>
+                      <artifactId>jta</artifactId>
+                    </exclusion>
+                    <exclusion>
+                        <groupId>commons-logging</groupId>
+                        <artifactId>commons-logging</artifactId>
+                    </exclusion>       
+                    <exclusion>
+                        <groupId>org.jboss</groupId>
+                        <artifactId>jboss-common-core</artifactId>
+                    </exclusion>                          
+                </exclusions>                
+			</dependency>
+            <dependency>
+                <groupId>org.jboss.man</groupId>
+                <artifactId>jboss-managed</artifactId>
+                <version>2.1.0.SP1</version>
+                <scope>provided</scope>
+            </dependency>        
+            <dependency>
+              <groupId>org.jboss.man</groupId>
+              <artifactId>jboss-metatype</artifactId>
+              <version>2.1.0.SP1</version>
+              <scope>provided</scope>
+            </dependency>            
+            <dependency>
+                <groupId>org.jboss.integration</groupId>
+                <artifactId>jboss-profileservice-spi</artifactId>
+                <version>5.1.0.GA</version>
+                <scope>provided</scope>
+            </dependency>      
+            <dependency>    
+                <groupId>org.jboss</groupId>
+                <artifactId>jboss-vfs</artifactId>
+                <version>2.1.2.GA</version>
+                <scope>provided</scope>
+            </dependency>
+            <dependency>    
+                <groupId>org.jboss.deployers</groupId>
+                <artifactId>jboss-deployers-vfs-spi</artifactId>
+                <version>2.0.7.GA</version>
+                <scope>provided</scope>
+            </dependency>      
+            <dependency>    
+                <groupId>org.jboss.deployers</groupId>
+                <artifactId>jboss-deployers-vfs</artifactId>
+                <version>2.0.7.GA</version>
+                <scope>provided</scope>
+            </dependency>              
+            <dependency>
+              <groupId>org.jboss.jbossas</groupId>
+              <artifactId>jboss-as-connector</artifactId>
+              <version>5.1.0.GA</version>
+              <scope>provided</scope>
+            </dependency>
+            <dependency>
+                <groupId>org.jboss</groupId>
+                <artifactId>jboss-reflect</artifactId>
+                <version>2.0.2.GA</version>
+                <scope>provided</scope>
+            </dependency>             
+            <dependency>
+              <groupId>org.jboss.remoting</groupId>
+              <artifactId>jboss-remoting</artifactId>
+              <version>2.5.1</version>
+              <scope>provided</scope>
+            </dependency>            
+			<dependency>
+				<groupId>net.sourceforge.saxon</groupId>
+				<artifactId>saxon</artifactId>
+				<version>9.1.0.8</version>
+			</dependency>
+			<dependency>
+				<groupId>net.sourceforge.saxon</groupId>
+				<artifactId>saxon</artifactId>
+				<classifier>dom</classifier>
+				<version>9.1.0.8</version>
+			</dependency>
+			<dependency>
+				<groupId>org.jboss.netty</groupId>
+				<artifactId>netty</artifactId>
+				<version>3.2.1.Final</version>
+			</dependency>
+			<dependency>
+				<groupId>org.apache.ant</groupId>
+				<artifactId>ant</artifactId>
+				<version>${ant.version}</version>
+			</dependency>
+			<dependency>
+  				<groupId>com.googlecode.json-simple</groupId>
+				<artifactId>json-simple</artifactId>
+  				<version>1.1</version>
+			</dependency>
+		</dependencies>
+	</dependencyManagement>
+	<modules>
+		<module>common-core</module>
+		<module>api</module>
+		<module>client</module>
+		<module>engine</module>
+		<module>connectors</module>
+		<module>console</module>
+		<module>metadata</module>
+		<module>runtime</module>
+		<module>adminshell</module>
+		<module>cache-jbosscache</module>
+		<module>hibernate-dialect</module>
+        <module>jboss-integration</module>
+		<module>test-integration</module>
+  </modules>
+    <distributionManagement>
+        <repository>
+            <id>jboss-releases-repository</id>
+            <name>JBoss Releases Repository</name>
+            <url>https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/</url>
+        </repository>
+        <snapshotRepository>
+            <id>jboss-snapshots-repository</id>
+            <name>JBoss Snapshots Repository</name>
+            <url>https://repository.jboss.org/nexus/content/repositories/snapshots/</url>
+        </snapshotRepository>
+    </distributionManagement>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/runtime/pom.xml
===================================================================
--- branches/7.2.x/runtime/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/runtime/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,94 +0,0 @@
-<?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">
-  <parent>
-    <artifactId>teiid-parent</artifactId>
-    <groupId>org.jboss.teiid</groupId>
-    <version>7.2.0.Final-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <groupId>org.jboss.teiid</groupId>
-  <artifactId>teiid-runtime</artifactId>
-  <name>Runtime Engine</name>
-  <description>Teiid Runtime Engine</description>
-  <dependencies>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <scope>provided</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <type>test-jar</type>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-api</artifactId>
-      <scope>provided</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-client</artifactId>
-      <scope>provided</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-engine</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-engine</artifactId>
-      <type>test-jar</type>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-metadata</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>log4j</groupId>
-      <artifactId>log4j</artifactId>
-      <scope>provided</scope>
-    </dependency>    
-    <dependency>
-        <groupId>commons-logging</groupId>
-        <artifactId>commons-logging</artifactId>
-        <scope>provided</scope>
-    </dependency>
-    <dependency>
-        <groupId>org.jboss.netty</groupId>
-        <artifactId>netty</artifactId>
-    </dependency>
-        
-    <dependency>
-        <groupId>org.jboss.cache</groupId>
-        <artifactId>jbosscache-core</artifactId>
-        <scope>test</scope>
-    </dependency>        
-    
-    <dependency>
-        <groupId>javax.resource</groupId>
-        <artifactId>connector-api</artifactId>
-        <scope>provided</scope>
-    </dependency>
-    <dependency>
-        <groupId>org.jboss</groupId>
-        <artifactId>jboss-vfs</artifactId>
-        <scope>provided</scope>
-    </dependency>    
-    <dependency>
-        <groupId>org.jboss.deployers</groupId>
-        <artifactId>jboss-deployers-vfs-spi</artifactId>
-        <scope>provided</scope>
-    </dependency> 
-    <dependency>    
-        <groupId>org.jboss.deployers</groupId>
-        <artifactId>jboss-deployers-vfs</artifactId>
-        <scope>provided</scope>
-    </dependency>    
-    <dependency>
-        <groupId>org.jboss.integration</groupId>
-        <artifactId>jboss-profileservice-spi</artifactId>
-        <scope>provided</scope>
-    </dependency>      
-  </dependencies>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/runtime/pom.xml (from rev 2708, branches/7.2.x/runtime/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/runtime/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/runtime/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,94 @@
+<?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">
+  <parent>
+    <artifactId>teiid-parent</artifactId>
+    <groupId>org.jboss.teiid</groupId>
+    <version>7.2.0.Final</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.jboss.teiid</groupId>
+  <artifactId>teiid-runtime</artifactId>
+  <name>Runtime Engine</name>
+  <description>Teiid Runtime Engine</description>
+  <dependencies>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <type>test-jar</type>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-api</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-client</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-engine</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-engine</artifactId>
+      <type>test-jar</type>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-metadata</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>log4j</groupId>
+      <artifactId>log4j</artifactId>
+      <scope>provided</scope>
+    </dependency>    
+    <dependency>
+        <groupId>commons-logging</groupId>
+        <artifactId>commons-logging</artifactId>
+        <scope>provided</scope>
+    </dependency>
+    <dependency>
+        <groupId>org.jboss.netty</groupId>
+        <artifactId>netty</artifactId>
+    </dependency>
+        
+    <dependency>
+        <groupId>org.jboss.cache</groupId>
+        <artifactId>jbosscache-core</artifactId>
+        <scope>test</scope>
+    </dependency>        
+    
+    <dependency>
+        <groupId>javax.resource</groupId>
+        <artifactId>connector-api</artifactId>
+        <scope>provided</scope>
+    </dependency>
+    <dependency>
+        <groupId>org.jboss</groupId>
+        <artifactId>jboss-vfs</artifactId>
+        <scope>provided</scope>
+    </dependency>    
+    <dependency>
+        <groupId>org.jboss.deployers</groupId>
+        <artifactId>jboss-deployers-vfs-spi</artifactId>
+        <scope>provided</scope>
+    </dependency> 
+    <dependency>    
+        <groupId>org.jboss.deployers</groupId>
+        <artifactId>jboss-deployers-vfs</artifactId>
+        <scope>provided</scope>
+    </dependency>    
+    <dependency>
+        <groupId>org.jboss.integration</groupId>
+        <artifactId>jboss-profileservice-spi</artifactId>
+        <scope>provided</scope>
+    </dependency>      
+  </dependencies>
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/runtime/src/main/java/org/teiid/transport/SocketConfiguration.java
===================================================================
--- branches/7.2.x/runtime/src/main/java/org/teiid/transport/SocketConfiguration.java	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/runtime/src/main/java/org/teiid/transport/SocketConfiguration.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,138 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.transport;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-import org.jboss.managed.api.annotation.ManagementComponent;
-import org.jboss.managed.api.annotation.ManagementObject;
-import org.jboss.managed.api.annotation.ManagementProperties;
-import org.jboss.managed.api.annotation.ManagementProperty;
-import org.teiid.core.TeiidRuntimeException;
-
-
- at ManagementObject(componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
-public class SocketConfiguration {
-	
-	private int outputBufferSize;
-	private int inputBufferSize;
-	private int maxSocketThreads;
-	private int portNumber;
-	private InetAddress hostAddress;
-	private SSLConfiguration sslConfiguration;
-	private boolean enabled;
-	private String hostName;
-	
-	
-	public void setBindAddress(String addr) {
-		this.hostName = addr;
-	}
-	
-	public void setPortNumber(int port) {
-		this.portNumber = port;
-	}
-	
-	public void setMaxSocketThreads(int value) {
-		this.maxSocketThreads = value;
-	}
-	
-	public void setInputBufferSize(int value) {
-		this.inputBufferSize = value;
-	}
-	
-	public void setOutputBufferSize(int value) {
-		this.outputBufferSize = value;
-	}
-	
-	public void setSSLConfiguration(SSLConfiguration value) {
-		this.sslConfiguration = value;
-	}	
- 	
-	private void resolveHostName() {
-		try {
-			// if not defined then see if can bind to local address; if supplied resolve it by name
-			if (this.hostName == null) {
-				this.hostName = InetAddress.getLocalHost().getHostName();
-			}
-		} catch (UnknownHostException e) {
-			throw new TeiidRuntimeException("Failed to resolve the bind address"); //$NON-NLS-1$
-		}
-	}
-
- 	@ManagementProperty(description="SSL enabled", readOnly=true)
-	public boolean isEnabled() {
-		return enabled;
-	}
-
-	public void setEnabled(boolean enabled) {
-		this.enabled = enabled;
-	}
-
-	@ManagementProperty(description="SO_SNDBUF size, 0 indicates that system default should be used (default 0)",readOnly=true)
-	public int getOutputBufferSize() {
-		return outputBufferSize;
-	}
-
-	@ManagementProperty(description="SO_RCVBUF size, 0 indicates that system default should be used (default 0)",readOnly=true)
-	public int getInputBufferSize() {
-		return inputBufferSize;
-	}
-
-	@ManagementProperty(description="Max NIO threads",readOnly=true)
-	public int getMaxSocketThreads() {
-		return maxSocketThreads;
-	}
-
-	@ManagementProperty(description="Port Number",readOnly=true)
-	public int getPortNumber() {
-		return portNumber;
-	}
-
-	public InetAddress getHostAddress() {
-		resolveHostName();
-		
-		if (this.hostAddress != null) {
-			return hostAddress;
-		}
-    	try {
-    		//only cache inetaddresses if they represent the ip. 
-			InetAddress addr = InetAddress.getByName(this.hostName);
-			if (addr.getHostAddress().equalsIgnoreCase(this.hostName)) {
-				this.hostAddress = addr;
-			}
-			return addr;
-		} catch (UnknownHostException e) {
-			throw new TeiidRuntimeException("Failed to resolve the bind address"); //$NON-NLS-1$
-		}		
-	}
-	
-	@ManagementProperty(description="Host Name",readOnly=true)
-	public String getHostName() {
-		resolveHostName();
-		return this.hostName;
-	}
-
-	public SSLConfiguration getSSLConfiguration() {
-		return sslConfiguration;
-	}	 	
-}

Copied: tags/teiid-parent-7.2.0.Final/runtime/src/main/java/org/teiid/transport/SocketConfiguration.java (from rev 2707, branches/7.2.x/runtime/src/main/java/org/teiid/transport/SocketConfiguration.java)
===================================================================
--- tags/teiid-parent-7.2.0.Final/runtime/src/main/java/org/teiid/transport/SocketConfiguration.java	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/runtime/src/main/java/org/teiid/transport/SocketConfiguration.java	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,154 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.transport;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+import org.jboss.managed.api.annotation.ManagementComponent;
+import org.jboss.managed.api.annotation.ManagementObject;
+import org.jboss.managed.api.annotation.ManagementObjectID;
+import org.jboss.managed.api.annotation.ManagementProperties;
+import org.jboss.managed.api.annotation.ManagementProperty;
+import org.teiid.core.TeiidRuntimeException;
+
+
+ at ManagementObject(componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
+public class SocketConfiguration {
+	
+	private int outputBufferSize;
+	private int inputBufferSize;
+	private int maxSocketThreads;
+	private int portNumber;
+	private InetAddress hostAddress;
+	private SSLConfiguration sslConfiguration;
+	private boolean enabled;
+	private String hostName;
+	private String name;
+	
+	@ManagementProperty(description="Name of the configuration", readOnly=true)
+	@ManagementObjectID(type="socket")
+	public String getName() {
+		return name;
+	}
+	
+	public void setName(String name) {
+		this.name = name;
+	}
+	
+	public void setBindAddress(String addr) {
+		this.hostName = addr;
+	}
+	
+	public void setPortNumber(int port) {
+		this.portNumber = port;
+	}
+	
+	public void setMaxSocketThreads(int value) {
+		this.maxSocketThreads = value;
+	}
+	
+	public void setInputBufferSize(int value) {
+		this.inputBufferSize = value;
+	}
+	
+	public void setOutputBufferSize(int value) {
+		this.outputBufferSize = value;
+	}
+	
+	public void setSSLConfiguration(SSLConfiguration value) {
+		this.sslConfiguration = value;
+	}	
+ 	
+	private void resolveHostName() {
+		try {
+			// if not defined then see if can bind to local address; if supplied resolve it by name
+			if (this.hostName == null) {
+				this.hostName = InetAddress.getLocalHost().getHostName();
+			}
+		} catch (UnknownHostException e) {
+			throw new TeiidRuntimeException("Failed to resolve the bind address"); //$NON-NLS-1$
+		}
+	}
+
+ 	@ManagementProperty(description="enabled")
+	public boolean getEnabled() {
+		return enabled;
+	}
+
+	public void setEnabled(boolean enabled) {
+		this.enabled = enabled;
+	}
+
+	@ManagementProperty(description="SO_SNDBUF size, 0 indicates that system default should be used (default 0)")
+	public int getOutputBufferSize() {
+		return outputBufferSize;
+	}
+
+	@ManagementProperty(description="SO_RCVBUF size, 0 indicates that system default should be used (default 0)")
+	public int getInputBufferSize() {
+		return inputBufferSize;
+	}
+
+	@ManagementProperty(description="Max NIO threads")
+	public int getMaxSocketThreads() {
+		return maxSocketThreads;
+	}
+
+	@ManagementProperty(description="Port Number")
+	public int getPortNumber() {
+		return portNumber;
+	}
+
+	public InetAddress getHostAddress() {
+		resolveHostName();
+		
+		if (this.hostAddress != null) {
+			return hostAddress;
+		}
+    	try {
+    		//only cache inetaddresses if they represent the ip. 
+			InetAddress addr = InetAddress.getByName(this.hostName);
+			if (addr.getHostAddress().equalsIgnoreCase(this.hostName)) {
+				this.hostAddress = addr;
+			}
+			return addr;
+		} catch (UnknownHostException e) {
+			throw new TeiidRuntimeException("Failed to resolve the bind address"); //$NON-NLS-1$
+		}		
+	}
+	
+	@ManagementProperty(description="Host Name")
+	public String getHostName() {
+		resolveHostName();
+		return this.hostName;
+	}
+
+	public SSLConfiguration getSSLConfiguration() {
+		return sslConfiguration;
+	}
+	
+	@ManagementProperty(description="SSL enabled")
+	public boolean getSslEnabled() {
+		return this.sslConfiguration != null && this.sslConfiguration.isSslEnabled();
+	}
+}

Deleted: tags/teiid-parent-7.2.0.Final/test-integration/common/pom.xml
===================================================================
--- branches/7.2.x/test-integration/common/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/test-integration/common/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,13 +0,0 @@
-<?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">
-	<parent>
-		<artifactId>teiid-test-integration</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>test-integration-common</artifactId>
-	<name>Common Integration Tests</name>
-	<description>Common Integration tests that do not require external dependencies</description>
-     
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/test-integration/common/pom.xml (from rev 2708, branches/7.2.x/test-integration/common/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/test-integration/common/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/test-integration/common/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,13 @@
+<?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">
+	<parent>
+		<artifactId>teiid-test-integration</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>test-integration-common</artifactId>
+	<name>Common Integration Tests</name>
+	<description>Common Integration tests that do not require external dependencies</description>
+     
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/test-integration/db/pom.xml
===================================================================
--- branches/7.2.x/test-integration/db/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/test-integration/db/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,537 +0,0 @@
-<?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">
-
-<!--
-	The database dependent tests are meant to be run on their own, not as part of the continous or nightly
-	build for Teiid.   
--->
-
-	<parent>
-		<artifactId>teiid-test-integration</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>test-integration-db</artifactId>
-
-	<name>DB Dependent Integration Tests</name>
- 	<groupId>org.jboss.teiid.teiid-test-integration</groupId>
-	<description>Integration tests that require external database dependencies </description>
-	<dependencies>
-
-		<dependency>
-			<groupId>junit</groupId>
-			<artifactId>junit</artifactId>
-			<version>4.4</version>
-		</dependency>
-	
-        <dependency>
-            <groupId>javax.transaction</groupId>
-            <artifactId>jta</artifactId>
-            <version>1.1</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-client</artifactId>
-        </dependency>
-			
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-			<type>test-jar</type>
-			<scope>compile</scope>
-		</dependency>
-
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-common-core</artifactId>
-        </dependency>
-
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-			<type>test-jar</type>
-			<scope>compile</scope>
-		</dependency>
-
-
-     
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-engine</artifactId>
-			<type>test-jar</type>
-			<scope>compile</scope>
-		</dependency> 
-		
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>test-integration-common</artifactId>
-			<type>test-jar</type>
-			<scope>compile</scope>
-			<version>${project.version}</version>
-		</dependency> 
-
-		<dependency>
-			<groupId>org.apache.ant</groupId>
-			<artifactId>ant</artifactId>
-			<version>1.7.0</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.apache.ant</groupId>
-			<artifactId>ant-launcher</artifactId>
-			<version>1.7.0</version>
-		</dependency>
-		<dependency>
-			<groupId>ant-contrib</groupId>
-			<artifactId>ant-contrib</artifactId>
-			<version>1.0b3</version>
-			<exclusions>
-                            <exclusion>
-                                <groupId>ant</groupId>
-                                <artifactId>ant</artifactId>
-                            </exclusion>
-    		</exclusions>
-
-		</dependency>
-
-		<dependency>
-			<groupId>ant-contrib</groupId>
-			<artifactId>cpptasks</artifactId>
-			<version>1.0b3</version>
-			<exclusions>
-                            <exclusion>
-                                <groupId>ant</groupId>
-                                <artifactId>ant</artifactId>
-                            </exclusion>
-    		</exclusions>
-		</dependency>
-
-
-	<!-- DBUnit dependencies -->
-		
-		<dependency>
-			<groupId>org.dbunit</groupId>
-			<artifactId>dbunit</artifactId>
-			<version>2.2</version>
-		</dependency>
-
-		<dependency>
-			<groupId>commons-collections</groupId>
-			<artifactId>commons-collections</artifactId>
-			<version>3.2.1</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.slf4j</groupId>
-			<artifactId>slf4j-api</artifactId>
-			<version>1.5.6</version>
-		</dependency>
-		
-
-		<dependency>
-			<groupId>org.apache.poi</groupId>
-			<artifactId>poi</artifactId>
-			<version>3.2-FINAL</version>
-		</dependency>
-
-		<dependency>
-			<groupId>jdom</groupId>
-			<artifactId>jdom</artifactId>
-			<version>1.0</version>
-		</dependency>
-
-            <dependency>
-                <groupId>postgresql</groupId>
-                <artifactId>postgresql</artifactId>
-                <version>${postgresql.version}</version>
-            </dependency>
-            <dependency>
-                <groupId>org.apache.derby</groupId>
-                <artifactId>derby</artifactId>
-                <version>${derby.version}</version>
-            </dependency>
-            <dependency>
-                <groupId>mysql</groupId>
-                <artifactId>mysql-connector-java</artifactId>
-                <version>${mysql.connector.version}</version>
-            </dependency>
-
-	</dependencies>	
-
-	 <profiles>
-        <profile>
-          <id>default</id>
-            <activation>
-                <activeByDefault>true</activeByDefault>
-            </activation>
-
-          <build>
-            <plugins>
-      <!-- Specify the compiler options and settings -->
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <configuration>
-                    <source>1.6</source>
-                    <target>1.6</target>
-                    <showDeprecation>false</showDeprecation>
-                    <showWarnings>false</showWarnings>
-                </configuration>
-            </plugin>
-                <plugin>
-                    <groupId>org.apache.maven.plugins</groupId>
-                    <artifactId>maven-surefire-plugin</artifactId>
-                    <configuration>
-                            <skip>true</skip>
-                    </configuration>
-                </plugin>   
-
-                    <plugin>
-                        <artifactId>maven-assembly-plugin</artifactId>
-                        <configuration>
-                            <descriptors>
-                                <descriptor>src/assembly/binaries.xml</descriptor>
-                            </descriptors>
-                            <outputDirectory>target/distribution</outputDirectory>
-                            <workDirectory>target/assembly/work</workDirectory>
-                        </configuration>
-                        <executions>
-                            <execution>
-                                <id>make-assembly</id>
-                                <phase>package</phase>
-                                <goals>
-                                    <goal>attached</goal>
-                                </goals>
-                            </execution>
-                        </executions>
-                    </plugin>
-            </plugins>
-        </build>
-    </profile>
-
-
-	    <profile>
-	      <id>runalltests</id>
-	      <build>
-			<plugins>
-			
-			<plugin>
-				<artifactId>maven-surefire-plugin</artifactId>
-				<configuration>
-		          <additionalClasspathElements>
-		                <additionalClasspathElement>${basedir}/lib/ojdbc6.jar</additionalClasspathElement>
-		                <additionalClasspathElement>${basedir}/lib/sqljdbc4.jar</additionalClasspathElement>
-		                <additionalClasspathElement>${basedir}/lib/db2jcc4.jar</additionalClasspathElement>
-
-		          </additionalClasspathElements>
-		          <systemProperties>
-		            <property>
-		              <name>usedatasources</name>
-		              <value>${usedatasources}</value>
-		            </property>
-		            <property>
-		              <name>datasourceloc</name>
-		              <value>${datasourceloc}</value>
-		            </property>
-		          </systemProperties>
-				
-<!-- 
-<forkMode>always</forkMode>
-					<forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
-			-->
-					<includes>
-			<!--			<include>**/*TestCase.java</include> -->
-						<include>**/*Test.java</include>
-						<include>**/*Tests.java</include>
-						<include>**/Test*.java</include>
-					</includes>
-					<excludes>
-						<exclude>**/*Abstract*TestCase.java</exclude>
-						<exclude>**/*Abstract*Test.java</exclude>
-			<!-- hack to prevent anonymous inner classes in Tests from being run as tests -->
-						<exclude>**/Test*$*.java</exclude>
-					</excludes>
-
-				</configuration>
-			</plugin>
-
-			</plugins>
-
-	      </build>
-
-<!-- 		        <version>2.4.2</version> -->
-
-		  <reporting>
-		    <plugins>
-		      <plugin>
-		        <groupId>org.apache.maven.plugins</groupId>
-		        <artifactId>maven-surefire-report-plugin</artifactId>
-
-		        <configuration>
-		           <outputDirectory>${basedir}/target/newsite</outputDirectory>
-		        </configuration>
-		      </plugin>
-		    </plugins>
-		  </reporting>
-	    </profile>
-
-	    <profile>
-	      <id>runsingletest</id>
-            <activation>
-                <property>
-                    <name>classname</name>
-                </property>
-            </activation>
-	      <build>
-			<plugins>
-
-			<plugin>
-				<artifactId>maven-surefire-plugin</artifactId>
-				<configuration>    		
-		          <additionalClasspathElements>
-		                <additionalClasspathElement>${basedir}/lib/ojdbc6.jar</additionalClasspathElement>
-		                <additionalClasspathElement>${basedir}/lib/sqljdbc4.jar</additionalClasspathElement>
-		                <additionalClasspathElement>${basedir}/lib/db2jcc4.jar</additionalClasspathElement>
- 		          </additionalClasspathElements>
-		          <systemProperties>
-		            <property>
-		              <name>usedatasources</name>
-		              <value>${usedatasources}</value>
-		            </property>
-		            <property>
-		              <name>datasourceloc</name>
-		              <value>${datasourceloc}</value>
-		            </property>
-		          </systemProperties>
-
-<!--
-					<forkMode>always</forkMode>
-
-					<forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
-	-->				
-					<includes>
-						<include>**/${classname}.java</include>
-					</includes>
-
-				</configuration>
-			</plugin>
-
-			</plugins>
-	      </build>
-	    </profile>
-
-
-	    <profile>
-	      <id>setupdatasources</id>
-	      <build>
-	        <plugins>
-
-    	<plugin>
-      		<groupId>org.apache.maven.plugins</groupId>
-      		<artifactId>maven-surefire-plugin</artifactId>
-      		<configuration>
-        			<skip>true</skip>
-     		</configuration>
-    	</plugin>
-	          <plugin>
-	          	<groupId>org.apache.maven.plugins</groupId>
-					<artifactId>maven-antrun-plugin</artifactId>
-					<dependencies>
-						<dependency>
-							<groupId>org.apache.ant</groupId>
-							<artifactId>ant</artifactId>
-							<version>${apache.ant.version}</version>
-						</dependency>
-					</dependencies>
-				<configuration>
-				</configuration>
-					<executions>
-						<execution>
-							<id>setupalldatasources</id>
-							<phase>pre-integration-test</phase>
-							<configuration>
-								<tasks>
-									<property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
-									<property name="relative.resources.dir" value="src/main/resources" />
-									<property name="datasourceloc" value="${datasourceloc}" />
-									<ant antfile="src/main/resources/ddl/manage_schemas.xml" />
-								</tasks>
-							</configuration>
-							<goals>
-								<goal>run</goal>
-							</goals>
-						</execution>
-	            </executions>
-	          </plugin>
-
-
-	        </plugins>
-	      </build>
-	    </profile>
-	    <profile>
-	      <id>singledatasource</id>
-    		<activation>
-      			<property>
-       		 		<name>datasource</name>
-      			</property>
-    		</activation>
-	      <build>
-	        <plugins>
-
-    	<plugin>
-      		<groupId>org.apache.maven.plugins</groupId>
-      		<artifactId>maven-surefire-plugin</artifactId>
-      		<configuration>
-        			<skip>true</skip>
-     		</configuration>
-    	</plugin>
-	          <plugin>
-	          	<groupId>org.apache.maven.plugins</groupId>
-					<artifactId>maven-antrun-plugin</artifactId>
-					<dependencies>
-						<dependency>
-							<groupId>org.apache.ant</groupId>
-							<artifactId>ant</artifactId>
-							<version>${apache.ant.version}</version>
-						</dependency>
-					</dependencies>
-	            <configuration>
-
-	            </configuration>
-					<executions>
-						<execution>
-							<id>setupsingledatasource</id>
-							<phase>pre-integration-test</phase>
-							<configuration>
-								<tasks>
-
-									<property name="single" value="${datasource}" />
-									<property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
-									<property name="datasourceloc" value="${datasourceloc}" />
-
-									<property name="relative.resources.dir" value="src/main/resources" />
-									<ant antfile="src/main/resources/ddl/manage_schemas.xml" />
-								</tasks>
-							</configuration>
-							<goals>
-								<goal>run</goal>
-							</goals>
-						</execution>
-	            </executions>
-	          </plugin>
-
-
-	        </plugins>
-	      </build>
-	    </profile>
-
-
-		<profile>
-	      <id>runclienttests</id>
-    		<activation>
-      			<property>
-       		 		<name>scenario.dir</name>
-      			</property>
-    		</activation>
-			<build>
-				<plugins>
-
-    	<plugin>
-      		<groupId>org.apache.maven.plugins</groupId>
-      		<artifactId>maven-surefire-plugin</artifactId>
-      		<configuration>
-        			<skip>true</skip>
-     		</configuration>
-    	</plugin>
-			<plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-antrun-plugin</artifactId>
-				<dependencies>
-					<dependency>
-						<groupId>org.apache.ant</groupId>
-						<artifactId>ant</artifactId>
-						<version>${apache.ant.version}</version>
-					</dependency>
-				</dependencies>
-				<executions>
-					<execution>
-						<id>run-client-test</id>
-						<phase>integration-test</phase>
-						<configuration>
-							<tasks>
-								
-								<property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
-								<property name="scenario.dir" value="${scenario.dir}" />
-								<property name="queryset.artifacts.dir" value="${queryset.artifacts.dir}" />
-								<property name="vdb.artifacts.dir" value="${vdb.artifacts.dir}" />
-								<!-- optional properties -->
-								<property name="config.file" value="${config.file}" />
-								<property name="query.scenario.classname" value="${query.scenario.classname}" />
-								<property name="proj.dir" value="${project.basedir}/target/" />
-								<property name="usedatasources" value="${usedatasources}" />
-								<property name="datasourceloc" value="${datasourceloc}" />
-
-								<ant antfile="src/main/resources/ctc_tests/ctc.xml" />
-
-							</tasks>
-						</configuration>
-						<goals>
-							<goal>run</goal>
-						</goals>
-					</execution>
-					
-				</executions>
-			</plugin>
-				</plugins>
-			</build>
-
-		</profile>
-
-		<profile>
-			<id>assemble</id>
-<!-- assemble will compile, but not run the tests prior to assemblying the kit -->
-
-			<build>
-			<plugins>
-
-		    	<plugin>
-		      		<groupId>org.apache.maven.plugins</groupId>
-		      		<artifactId>maven-surefire-plugin</artifactId>
-		      		<configuration>
-		        			<skip>true</skip>
-		     		</configuration>
-		    	</plugin>	
-
-				<plugin>
-					<artifactId>maven-assembly-plugin</artifactId>
-					<configuration>
-						<descriptors>
-							<descriptor>src/assembly/binaries.xml</descriptor>
-						</descriptors>
-						<outputDirectory>target/distribution</outputDirectory>
-						<workDirectory>target/work/assembly</workDirectory>
-
-					</configuration>
-					<executions>
-
-						<execution>
-							<id>make-assembly</id>
-							<phase>package</phase>
-							<goals>
-								<goal>attached</goal>
-							</goals>
-						</execution>
-					</executions>
-				</plugin>
-
-				</plugins>
-			</build>
-		</profile>
-
-	</profiles>
-
-
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/test-integration/db/pom.xml (from rev 2708, branches/7.2.x/test-integration/db/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/test-integration/db/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/test-integration/db/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,537 @@
+<?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">
+
+<!--
+	The database dependent tests are meant to be run on their own, not as part of the continous or nightly
+	build for Teiid.   
+-->
+
+	<parent>
+		<artifactId>teiid-test-integration</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>test-integration-db</artifactId>
+
+	<name>DB Dependent Integration Tests</name>
+ 	<groupId>org.jboss.teiid.teiid-test-integration</groupId>
+	<description>Integration tests that require external database dependencies </description>
+	<dependencies>
+
+		<dependency>
+			<groupId>junit</groupId>
+			<artifactId>junit</artifactId>
+			<version>4.4</version>
+		</dependency>
+	
+        <dependency>
+            <groupId>javax.transaction</groupId>
+            <artifactId>jta</artifactId>
+            <version>1.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-client</artifactId>
+        </dependency>
+			
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-client</artifactId>
+			<type>test-jar</type>
+			<scope>compile</scope>
+		</dependency>
+
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-common-core</artifactId>
+        </dependency>
+
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-common-core</artifactId>
+			<type>test-jar</type>
+			<scope>compile</scope>
+		</dependency>
+
+
+     
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-engine</artifactId>
+			<type>test-jar</type>
+			<scope>compile</scope>
+		</dependency> 
+		
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>test-integration-common</artifactId>
+			<type>test-jar</type>
+			<scope>compile</scope>
+			<version>${project.version}</version>
+		</dependency> 
+
+		<dependency>
+			<groupId>org.apache.ant</groupId>
+			<artifactId>ant</artifactId>
+			<version>1.7.0</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.apache.ant</groupId>
+			<artifactId>ant-launcher</artifactId>
+			<version>1.7.0</version>
+		</dependency>
+		<dependency>
+			<groupId>ant-contrib</groupId>
+			<artifactId>ant-contrib</artifactId>
+			<version>1.0b3</version>
+			<exclusions>
+                            <exclusion>
+                                <groupId>ant</groupId>
+                                <artifactId>ant</artifactId>
+                            </exclusion>
+    		</exclusions>
+
+		</dependency>
+
+		<dependency>
+			<groupId>ant-contrib</groupId>
+			<artifactId>cpptasks</artifactId>
+			<version>1.0b3</version>
+			<exclusions>
+                            <exclusion>
+                                <groupId>ant</groupId>
+                                <artifactId>ant</artifactId>
+                            </exclusion>
+    		</exclusions>
+		</dependency>
+
+
+	<!-- DBUnit dependencies -->
+		
+		<dependency>
+			<groupId>org.dbunit</groupId>
+			<artifactId>dbunit</artifactId>
+			<version>2.2</version>
+		</dependency>
+
+		<dependency>
+			<groupId>commons-collections</groupId>
+			<artifactId>commons-collections</artifactId>
+			<version>3.2.1</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.slf4j</groupId>
+			<artifactId>slf4j-api</artifactId>
+			<version>1.5.6</version>
+		</dependency>
+		
+
+		<dependency>
+			<groupId>org.apache.poi</groupId>
+			<artifactId>poi</artifactId>
+			<version>3.2-FINAL</version>
+		</dependency>
+
+		<dependency>
+			<groupId>jdom</groupId>
+			<artifactId>jdom</artifactId>
+			<version>1.0</version>
+		</dependency>
+
+            <dependency>
+                <groupId>postgresql</groupId>
+                <artifactId>postgresql</artifactId>
+                <version>${postgresql.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.derby</groupId>
+                <artifactId>derby</artifactId>
+                <version>${derby.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>mysql</groupId>
+                <artifactId>mysql-connector-java</artifactId>
+                <version>${mysql.connector.version}</version>
+            </dependency>
+
+	</dependencies>	
+
+	 <profiles>
+        <profile>
+          <id>default</id>
+            <activation>
+                <activeByDefault>true</activeByDefault>
+            </activation>
+
+          <build>
+            <plugins>
+      <!-- Specify the compiler options and settings -->
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>1.6</source>
+                    <target>1.6</target>
+                    <showDeprecation>false</showDeprecation>
+                    <showWarnings>false</showWarnings>
+                </configuration>
+            </plugin>
+                <plugin>
+                    <groupId>org.apache.maven.plugins</groupId>
+                    <artifactId>maven-surefire-plugin</artifactId>
+                    <configuration>
+                            <skip>true</skip>
+                    </configuration>
+                </plugin>   
+
+                    <plugin>
+                        <artifactId>maven-assembly-plugin</artifactId>
+                        <configuration>
+                            <descriptors>
+                                <descriptor>src/assembly/binaries.xml</descriptor>
+                            </descriptors>
+                            <outputDirectory>target/distribution</outputDirectory>
+                            <workDirectory>target/assembly/work</workDirectory>
+                        </configuration>
+                        <executions>
+                            <execution>
+                                <id>make-assembly</id>
+                                <phase>package</phase>
+                                <goals>
+                                    <goal>attached</goal>
+                                </goals>
+                            </execution>
+                        </executions>
+                    </plugin>
+            </plugins>
+        </build>
+    </profile>
+
+
+	    <profile>
+	      <id>runalltests</id>
+	      <build>
+			<plugins>
+			
+			<plugin>
+				<artifactId>maven-surefire-plugin</artifactId>
+				<configuration>
+		          <additionalClasspathElements>
+		                <additionalClasspathElement>${basedir}/lib/ojdbc6.jar</additionalClasspathElement>
+		                <additionalClasspathElement>${basedir}/lib/sqljdbc4.jar</additionalClasspathElement>
+		                <additionalClasspathElement>${basedir}/lib/db2jcc4.jar</additionalClasspathElement>
+
+		          </additionalClasspathElements>
+		          <systemProperties>
+		            <property>
+		              <name>usedatasources</name>
+		              <value>${usedatasources}</value>
+		            </property>
+		            <property>
+		              <name>datasourceloc</name>
+		              <value>${datasourceloc}</value>
+		            </property>
+		          </systemProperties>
+				
+<!-- 
+<forkMode>always</forkMode>
+					<forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
+			-->
+					<includes>
+			<!--			<include>**/*TestCase.java</include> -->
+						<include>**/*Test.java</include>
+						<include>**/*Tests.java</include>
+						<include>**/Test*.java</include>
+					</includes>
+					<excludes>
+						<exclude>**/*Abstract*TestCase.java</exclude>
+						<exclude>**/*Abstract*Test.java</exclude>
+			<!-- hack to prevent anonymous inner classes in Tests from being run as tests -->
+						<exclude>**/Test*$*.java</exclude>
+					</excludes>
+
+				</configuration>
+			</plugin>
+
+			</plugins>
+
+	      </build>
+
+<!-- 		        <version>2.4.2</version> -->
+
+		  <reporting>
+		    <plugins>
+		      <plugin>
+		        <groupId>org.apache.maven.plugins</groupId>
+		        <artifactId>maven-surefire-report-plugin</artifactId>
+
+		        <configuration>
+		           <outputDirectory>${basedir}/target/newsite</outputDirectory>
+		        </configuration>
+		      </plugin>
+		    </plugins>
+		  </reporting>
+	    </profile>
+
+	    <profile>
+	      <id>runsingletest</id>
+            <activation>
+                <property>
+                    <name>classname</name>
+                </property>
+            </activation>
+	      <build>
+			<plugins>
+
+			<plugin>
+				<artifactId>maven-surefire-plugin</artifactId>
+				<configuration>    		
+		          <additionalClasspathElements>
+		                <additionalClasspathElement>${basedir}/lib/ojdbc6.jar</additionalClasspathElement>
+		                <additionalClasspathElement>${basedir}/lib/sqljdbc4.jar</additionalClasspathElement>
+		                <additionalClasspathElement>${basedir}/lib/db2jcc4.jar</additionalClasspathElement>
+ 		          </additionalClasspathElements>
+		          <systemProperties>
+		            <property>
+		              <name>usedatasources</name>
+		              <value>${usedatasources}</value>
+		            </property>
+		            <property>
+		              <name>datasourceloc</name>
+		              <value>${datasourceloc}</value>
+		            </property>
+		          </systemProperties>
+
+<!--
+					<forkMode>always</forkMode>
+
+					<forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
+	-->				
+					<includes>
+						<include>**/${classname}.java</include>
+					</includes>
+
+				</configuration>
+			</plugin>
+
+			</plugins>
+	      </build>
+	    </profile>
+
+
+	    <profile>
+	      <id>setupdatasources</id>
+	      <build>
+	        <plugins>
+
+    	<plugin>
+      		<groupId>org.apache.maven.plugins</groupId>
+      		<artifactId>maven-surefire-plugin</artifactId>
+      		<configuration>
+        			<skip>true</skip>
+     		</configuration>
+    	</plugin>
+	          <plugin>
+	          	<groupId>org.apache.maven.plugins</groupId>
+					<artifactId>maven-antrun-plugin</artifactId>
+					<dependencies>
+						<dependency>
+							<groupId>org.apache.ant</groupId>
+							<artifactId>ant</artifactId>
+							<version>${apache.ant.version}</version>
+						</dependency>
+					</dependencies>
+				<configuration>
+				</configuration>
+					<executions>
+						<execution>
+							<id>setupalldatasources</id>
+							<phase>pre-integration-test</phase>
+							<configuration>
+								<tasks>
+									<property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
+									<property name="relative.resources.dir" value="src/main/resources" />
+									<property name="datasourceloc" value="${datasourceloc}" />
+									<ant antfile="src/main/resources/ddl/manage_schemas.xml" />
+								</tasks>
+							</configuration>
+							<goals>
+								<goal>run</goal>
+							</goals>
+						</execution>
+	            </executions>
+	          </plugin>
+
+
+	        </plugins>
+	      </build>
+	    </profile>
+	    <profile>
+	      <id>singledatasource</id>
+    		<activation>
+      			<property>
+       		 		<name>datasource</name>
+      			</property>
+    		</activation>
+	      <build>
+	        <plugins>
+
+    	<plugin>
+      		<groupId>org.apache.maven.plugins</groupId>
+      		<artifactId>maven-surefire-plugin</artifactId>
+      		<configuration>
+        			<skip>true</skip>
+     		</configuration>
+    	</plugin>
+	          <plugin>
+	          	<groupId>org.apache.maven.plugins</groupId>
+					<artifactId>maven-antrun-plugin</artifactId>
+					<dependencies>
+						<dependency>
+							<groupId>org.apache.ant</groupId>
+							<artifactId>ant</artifactId>
+							<version>${apache.ant.version}</version>
+						</dependency>
+					</dependencies>
+	            <configuration>
+
+	            </configuration>
+					<executions>
+						<execution>
+							<id>setupsingledatasource</id>
+							<phase>pre-integration-test</phase>
+							<configuration>
+								<tasks>
+
+									<property name="single" value="${datasource}" />
+									<property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
+									<property name="datasourceloc" value="${datasourceloc}" />
+
+									<property name="relative.resources.dir" value="src/main/resources" />
+									<ant antfile="src/main/resources/ddl/manage_schemas.xml" />
+								</tasks>
+							</configuration>
+							<goals>
+								<goal>run</goal>
+							</goals>
+						</execution>
+	            </executions>
+	          </plugin>
+
+
+	        </plugins>
+	      </build>
+	    </profile>
+
+
+		<profile>
+	      <id>runclienttests</id>
+    		<activation>
+      			<property>
+       		 		<name>scenario.dir</name>
+      			</property>
+    		</activation>
+			<build>
+				<plugins>
+
+    	<plugin>
+      		<groupId>org.apache.maven.plugins</groupId>
+      		<artifactId>maven-surefire-plugin</artifactId>
+      		<configuration>
+        			<skip>true</skip>
+     		</configuration>
+    	</plugin>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-antrun-plugin</artifactId>
+				<dependencies>
+					<dependency>
+						<groupId>org.apache.ant</groupId>
+						<artifactId>ant</artifactId>
+						<version>${apache.ant.version}</version>
+					</dependency>
+				</dependencies>
+				<executions>
+					<execution>
+						<id>run-client-test</id>
+						<phase>integration-test</phase>
+						<configuration>
+							<tasks>
+								
+								<property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
+								<property name="scenario.dir" value="${scenario.dir}" />
+								<property name="queryset.artifacts.dir" value="${queryset.artifacts.dir}" />
+								<property name="vdb.artifacts.dir" value="${vdb.artifacts.dir}" />
+								<!-- optional properties -->
+								<property name="config.file" value="${config.file}" />
+								<property name="query.scenario.classname" value="${query.scenario.classname}" />
+								<property name="proj.dir" value="${project.basedir}/target/" />
+								<property name="usedatasources" value="${usedatasources}" />
+								<property name="datasourceloc" value="${datasourceloc}" />
+
+								<ant antfile="src/main/resources/ctc_tests/ctc.xml" />
+
+							</tasks>
+						</configuration>
+						<goals>
+							<goal>run</goal>
+						</goals>
+					</execution>
+					
+				</executions>
+			</plugin>
+				</plugins>
+			</build>
+
+		</profile>
+
+		<profile>
+			<id>assemble</id>
+<!-- assemble will compile, but not run the tests prior to assemblying the kit -->
+
+			<build>
+			<plugins>
+
+		    	<plugin>
+		      		<groupId>org.apache.maven.plugins</groupId>
+		      		<artifactId>maven-surefire-plugin</artifactId>
+		      		<configuration>
+		        			<skip>true</skip>
+		     		</configuration>
+		    	</plugin>	
+
+				<plugin>
+					<artifactId>maven-assembly-plugin</artifactId>
+					<configuration>
+						<descriptors>
+							<descriptor>src/assembly/binaries.xml</descriptor>
+						</descriptors>
+						<outputDirectory>target/distribution</outputDirectory>
+						<workDirectory>target/work/assembly</workDirectory>
+
+					</configuration>
+					<executions>
+
+						<execution>
+							<id>make-assembly</id>
+							<phase>package</phase>
+							<goals>
+								<goal>attached</goal>
+							</goals>
+						</execution>
+					</executions>
+				</plugin>
+
+				</plugins>
+			</build>
+		</profile>
+
+	</profiles>
+
+
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.2.0.Final/test-integration/pom.xml
===================================================================
--- branches/7.2.x/test-integration/pom.xml	2010-11-05 02:27:49 UTC (rev 2706)
+++ tags/teiid-parent-7.2.0.Final/test-integration/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -1,107 +0,0 @@
-<?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">
-	<parent>
-		<artifactId>teiid-parent</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.2.0.Final-SNAPSHOT</version>
-	</parent>
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>teiid-test-integration</artifactId>
-  	<packaging>pom</packaging>
-	<name>Integration Tests</name>
-	<description>Integration tests spanning	server/embedded/connectors.</description>
-
-	<properties>
-		<derby.version>10.2.1.6</derby.version>
-		<mysql.connector.version>5.1.5</mysql.connector.version>
-		<postgresql.version>8.3-603.jdbc3</postgresql.version>
-
-		<apache.ant.version>1.7.0</apache.ant.version>
-	</properties>
-
-	<dependencies>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-			<type>test-jar</type>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-metadata</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-metadata</artifactId>
-			<type>test-jar</type>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-api</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid.connectors</groupId>
-			<artifactId>translator-jdbc</artifactId>
-			<version>${project.version}</version>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-			<type>test-jar</type>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-engine</artifactId>
-			<type>test-jar</type>
-		</dependency>
-        <dependency>
-            <groupId>org.jboss.teiid</groupId>
-            <artifactId>teiid-adminshell</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-        <dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-runtime</artifactId>
-		</dependency>
-
-		<!-- external dependencies -->
-		<dependency>
-			<groupId>org.apache.derby</groupId>
-			<artifactId>derby</artifactId>
-			<version>${derby.version}</version>
-
-		</dependency>
-		
-		<dependency>
-      		<groupId>javax.resource</groupId>
-      		<artifactId>connector-api</artifactId>
-      		<scope>provided</scope>
-    	</dependency>
-    	
-    	<dependency>
-			<groupId>javax.transaction</groupId>
-                <artifactId>jta</artifactId>
-		</dependency>
-
-        <dependency>
-            <groupId>org.jboss.deployers</groupId>
-            <artifactId>jboss-deployers-vfs-spi</artifactId>
-            <scope>provided</scope>
-        </dependency> 
-        
-        <dependency>    
-            <groupId>org.jboss.deployers</groupId>
-            <artifactId>jboss-deployers-vfs</artifactId>
-            <scope>provided</scope>
-        </dependency>   		
-        
-	</dependencies>
-
-  <modules>
-    <module>common</module>
-    <module>db</module>
-  </modules>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.2.0.Final/test-integration/pom.xml (from rev 2708, branches/7.2.x/test-integration/pom.xml)
===================================================================
--- tags/teiid-parent-7.2.0.Final/test-integration/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.2.0.Final/test-integration/pom.xml	2010-11-05 03:19:55 UTC (rev 2709)
@@ -0,0 +1,107 @@
+<?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">
+	<parent>
+		<artifactId>teiid-parent</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.2.0.Final</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>teiid-test-integration</artifactId>
+  	<packaging>pom</packaging>
+	<name>Integration Tests</name>
+	<description>Integration tests spanning	server/embedded/connectors.</description>
+
+	<properties>
+		<derby.version>10.2.1.6</derby.version>
+		<mysql.connector.version>5.1.5</mysql.connector.version>
+		<postgresql.version>8.3-603.jdbc3</postgresql.version>
+
+		<apache.ant.version>1.7.0</apache.ant.version>
+	</properties>
+
+	<dependencies>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-common-core</artifactId>
+			<type>test-jar</type>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-metadata</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-metadata</artifactId>
+			<type>test-jar</type>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-api</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid.connectors</groupId>
+			<artifactId>translator-jdbc</artifactId>
+			<version>${project.version}</version>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-client</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-client</artifactId>
+			<type>test-jar</type>
+		</dependency>
+		<dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-engine</artifactId>
+			<type>test-jar</type>
+		</dependency>
+        <dependency>
+            <groupId>org.jboss.teiid</groupId>
+            <artifactId>teiid-adminshell</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+			<groupId>org.jboss.teiid</groupId>
+			<artifactId>teiid-runtime</artifactId>
+		</dependency>
+
+		<!-- external dependencies -->
+		<dependency>
+			<groupId>org.apache.derby</groupId>
+			<artifactId>derby</artifactId>
+			<version>${derby.version}</version>
+
+		</dependency>
+		
+		<dependency>
+      		<groupId>javax.resource</groupId>
+      		<artifactId>connector-api</artifactId>
+      		<scope>provided</scope>
+    	</dependency>
+    	
+    	<dependency>
+			<groupId>javax.transaction</groupId>
+                <artifactId>jta</artifactId>
+		</dependency>
+
+        <dependency>
+            <groupId>org.jboss.deployers</groupId>
+            <artifactId>jboss-deployers-vfs-spi</artifactId>
+            <scope>provided</scope>
+        </dependency> 
+        
+        <dependency>    
+            <groupId>org.jboss.deployers</groupId>
+            <artifactId>jboss-deployers-vfs</artifactId>
+            <scope>provided</scope>
+        </dependency>   		
+        
+	</dependencies>
+
+  <modules>
+    <module>common</module>
+    <module>db</module>
+  </modules>
+</project>
\ No newline at end of file



More information about the teiid-commits mailing list