[teiid-commits] teiid SVN: r2805 - in tags: teiid-parent-7.3.0.Alpha2 and 65 other directories.

teiid-commits at lists.jboss.org teiid-commits at lists.jboss.org
Fri Dec 24 14:07:04 EST 2010


Author: shawkins
Date: 2010-12-24 14:07:00 -0500 (Fri, 24 Dec 2010)
New Revision: 2805

Added:
   tags/teiid-parent-7.3.0.Alpha2/
   tags/teiid-parent-7.3.0.Alpha2/adminshell/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/api/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/build/kits/jboss-container/teiid-examples/jca/odbc-ds.xml
   tags/teiid-parent-7.3.0.Alpha2/build/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/cache-jbosscache/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/client/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java
   tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java
   tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/netty/handler/codec/serialization/CompactObjectOutputStream.java
   tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/jdbc/TestPreparedStatement.java
   tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/netty/handler/codec/serialization/TestObjectDecoderInputStream.java
   tags/teiid-parent-7.3.0.Alpha2/common-core/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/types/InputStreamFactory.java
   tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-file/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ldap/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ws/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/salesforce-api/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/translator-yahoo/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-delegate/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-file/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-jdbc/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ldap/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-loopback/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/Util.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/visitors/CriteriaVisitor.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ws/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/console/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/admin-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/caching-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/client-developers-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/developer-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/quick-start-example/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/reference/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/reference/src/main/docbook/en-US/content/system_schema.xml
   tags/teiid-parent-7.3.0.Alpha2/engine/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/LobManager.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/TransactionServerImpl.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/processor/xml/XMLUtil.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/sql/lang/Query.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/query/resolver/TestResolver.java
   tags/teiid-parent-7.3.0.Alpha2/hibernate-dialect/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/jboss-integration/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
   tags/teiid-parent-7.3.0.Alpha2/metadata/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/runtime/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/Log4jListener.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistry.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistryImpl.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/org/teiid/runtime/i18n.properties
   tags/teiid-parent-7.3.0.Alpha2/test-integration/common/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/test-integration/db/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/test-integration/pom.xml
Removed:
   tags/teiid-parent-7.3.0.Alpha2/adminshell/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/api/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/build/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/cache-jbosscache/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/client/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java
   tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java
   tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/netty/handler/codec/serialization/CompactObjectOutputStream.java
   tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/jdbc/TestPreparedStatement.java
   tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/netty/handler/codec/serialization/TestObjectDecoderInputStream.java
   tags/teiid-parent-7.3.0.Alpha2/common-core/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/types/InputStreamFactory.java
   tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-file/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ldap/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ws/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/salesforce-api/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/translator-yahoo/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-delegate/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-file/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-jdbc/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ldap/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-loopback/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/Util.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/visitors/CriteriaVisitor.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java
   tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ws/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/console/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/admin-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/caching-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/client-developers-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/developer-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/quick-start-example/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/reference/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/documentation/reference/src/main/docbook/en-US/content/system_schema.xml
   tags/teiid-parent-7.3.0.Alpha2/engine/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/LobManager.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/TransactionServerImpl.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/processor/xml/XMLUtil.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/sql/lang/Query.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
   tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/query/resolver/TestResolver.java
   tags/teiid-parent-7.3.0.Alpha2/hibernate-dialect/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/jboss-integration/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
   tags/teiid-parent-7.3.0.Alpha2/metadata/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/runtime/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/CommonsLogManagerAdapter.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/Log4jListener.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistry.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistryImpl.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/commons-logging.properties
   tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/org/teiid/runtime/i18n.properties
   tags/teiid-parent-7.3.0.Alpha2/test-integration/common/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/test-integration/db/pom.xml
   tags/teiid-parent-7.3.0.Alpha2/test-integration/pom.xml
Log:
[maven-release-plugin]  copy for tag teiid-parent-7.3.0.Alpha2

Copied: tags/teiid-parent-7.3.0.Alpha2 (from rev 2800, trunk)

Deleted: tags/teiid-parent-7.3.0.Alpha2/adminshell/pom.xml
===================================================================
--- trunk/adminshell/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/adminshell/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/adminshell/pom.xml (from rev 2804, trunk/adminshell/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/adminshell/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/adminshell/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/api/pom.xml
===================================================================
--- trunk/api/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/api/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/api/pom.xml (from rev 2804, trunk/api/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/api/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/api/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/build/kits/jboss-container/teiid-examples/jca/odbc-ds.xml (from rev 2802, trunk/build/kits/jboss-container/teiid-examples/jca/odbc-ds.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/build/kits/jboss-container/teiid-examples/jca/odbc-ds.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/build/kits/jboss-container/teiid-examples/jca/odbc-ds.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<datasources>
+    <!-- Sample data source using JDBC-ODBC bridge to connect to ODBC source  -->
+    <no-tx-datasource>
+        <jndi-name>odbcDS</jndi-name>
+
+        <!-- Create a DSN using ODBC driver manager, and replace {DSN} below with your DSN name -->
+        <connection-url>jdbc:odbc:{DSN}</connection-url>
+        
+        <!-- For DSN less connection URL use the below form to connect to a Excel Sheet
+          <connection-url>jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};Dbq=c:\ODBC\ExcelData.xls</connection-url>
+        -->
+         
+        <driver-class>sun.jdbc.odbc.JdbcOdbcDriver</driver-class>
+        
+        <transaction-isolation>TRANSACTION_NONE</transaction-isolation>
+        <min-pool-size>1</min-pool-size>
+        <max-pool-size>1</max-pool-size>
+        <idle-timeout-minutes>5</idle-timeout-minutes>
+    </no-tx-datasource>
+
+</datasources> 
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha2/build/pom.xml
===================================================================
--- trunk/build/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/build/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/build/pom.xml (from rev 2804, trunk/build/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/build/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/build/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/cache-jbosscache/pom.xml
===================================================================
--- trunk/cache-jbosscache/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/cache-jbosscache/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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>
-        <dependency>
-            <groupId>org.jboss.man</groupId>
-            <artifactId>jboss-managed</artifactId>
-            <scope>provided</scope>
-        </dependency>        
-	</dependencies>
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha2/cache-jbosscache/pom.xml (from rev 2804, trunk/cache-jbosscache/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/cache-jbosscache/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/cache-jbosscache/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/client/pom.xml
===================================================================
--- trunk/client/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/client/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/client/pom.xml (from rev 2804, trunk/client/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/client/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/client/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java
===================================================================
--- trunk/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,775 +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.jdbc;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.math.BigDecimal;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.sql.Array;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.NClob;
-import java.sql.ParameterMetaData;
-import java.sql.PreparedStatement;
-import java.sql.Ref;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.RowId;
-import java.sql.SQLException;
-import java.sql.SQLXML;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.TimeZone;
-import java.util.TreeMap;
-
-import javax.sql.rowset.serial.SerialBlob;
-
-import org.teiid.client.RequestMessage;
-import org.teiid.client.RequestMessage.ResultsMode;
-import org.teiid.client.RequestMessage.StatementType;
-import org.teiid.client.metadata.MetadataResult;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.BlobImpl;
-import org.teiid.core.types.ClobImpl;
-import org.teiid.core.types.InputStreamFactory;
-import org.teiid.core.types.JDBCSQLTypeInfo;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.util.ArgCheck;
-import org.teiid.core.util.ReaderInputStream;
-import org.teiid.core.util.SqlUtil;
-import org.teiid.core.util.TimestampWithTimezone;
-
-
-/**
- * <p> Instances of PreparedStatement contain a SQL statement that has already been
- * compiled.  The SQL statement contained in a PreparedStatement object may have
- * one or more IN parameters. An IN parameter is a parameter whose value is not
- * specified when a SQL statement is created. Instead the statement has a placeholder
- * for each IN parameter.</p>
- * <p> The MMPreparedStatement object wraps the server's PreparedStatement object.
- * The methods in this class are used to set the IN parameters on a server's
- * preparedstatement object.</p>
- */
-
-public class PreparedStatementImpl extends StatementImpl implements PreparedStatement {
-    // sql, which this prepared statement is operating on
-    protected String prepareSql;
-
-    //map that holds parameter index to values for prepared statements
-    private Map<Integer, Object> parameterMap;
-    
-    //a list of map that holds parameter index to values for prepared statements
-    protected List<List<Object>> batchParameterList;
-
-    // metadata
-	private MetadataResult metadataResults;
-    private ResultSetMetaData metadata;
-    private ParameterMetaData parameterMetaData;
-    
-    private Calendar serverCalendar;
-
-    /**
-     * Factory Constructor 
-     * @param connection
-     * @param sql
-     * @param resultSetType
-     * @param resultSetConcurrency
-     */
-    static PreparedStatementImpl newInstance(ConnectionImpl connection, String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
-        return new PreparedStatementImpl(connection, sql, resultSetType, resultSetConcurrency);        
-    }
-    
-    /**
-     * <p>MMPreparedStatement constructor.
-     * @param Driver's connection object.
-     * @param String object representing the prepared statement
-     */
-    PreparedStatementImpl(ConnectionImpl connection, String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
-        super(connection, resultSetType, resultSetConcurrency);
-
-        // this sql is for callable statement, don't check any more
-        ArgCheck.isNotNull(sql, JDBCPlugin.Util.getString("MMPreparedStatement.Err_prep_sql")); //$NON-NLS-1$
-        this.prepareSql = sql;
-
-        TimeZone timezone = connection.getServerConnection().getLogonResult().getTimeZone();
-
-        if (timezone != null && !timezone.hasSameRules(getDefaultCalendar().getTimeZone())) {
-        	this.serverCalendar = Calendar.getInstance(timezone);
-        }        
-    }
-
-    /**
-     * <p>Adds a set of parameters to this PreparedStatement object's list of commands
-     * to be sent to the database for execution as a batch.
-     * @throws SQLException if there is an error
-     */
-    public void addBatch() throws SQLException {
-        checkStatement();
-    	if(batchParameterList == null){
-    		batchParameterList = new ArrayList<List<Object>>();
-		}
-    	batchParameterList.add(getParameterValues());
-		clearParameters();
-    }
-
-    /**
-     * Makes the set of commands in the current batch empty.
-     *
-     * @throws SQLException if a database access error occurs or the
-     * driver does not support batch statements
-     */
-    public void clearBatch() throws SQLException {
-    	if (batchParameterList != null ) {
-    		batchParameterList.clear();
-    	}
-    }
-
-    /**
-     * <p>Clears the values set for the PreparedStatement object's IN parameters and
-     * releases the resources used by those values. In general, parameter values
-     * remain in force for repeated use of statement.
-     * @throws SQLException if there is an error while clearing params
-     */
-    public void clearParameters() throws SQLException {
-        checkStatement();
-        //clear the parameters list on servers prepared statement object
-        if(parameterMap != null){
-            parameterMap.clear();
-        }
-    }
-    
-    @Override
-    public boolean execute(String sql) throws SQLException {
-    	String msg = JDBCPlugin.Util.getString("JDBC.Method_not_supported"); //$NON-NLS-1$
-        throw new TeiidSQLException(msg);
-    }
-    
-    @Override
-    public ResultSet executeQuery(String sql) throws SQLException {
-    	String msg = JDBCPlugin.Util.getString("JDBC.Method_not_supported"); //$NON-NLS-1$
-        throw new TeiidSQLException(msg);
-    }
-    
-    @Override
-    public int executeUpdate(String sql) throws SQLException {
-    	String msg = JDBCPlugin.Util.getString("JDBC.Method_not_supported"); //$NON-NLS-1$
-        throw new TeiidSQLException(msg);
-    }
-    
-    @Override
-    public void addBatch(String sql) throws SQLException {
-    	String msg = JDBCPlugin.Util.getString("JDBC.Method_not_supported"); //$NON-NLS-1$
-        throw new TeiidSQLException(msg);
-    }
-
-	@Override
-    public boolean execute() throws SQLException {
-        executeSql(new String[] {this.prepareSql}, false, ResultsMode.EITHER);
-        return hasResultSet();
-    }
-    
-    @Override
-    public int[] executeBatch() throws SQLException {
-    	if (batchParameterList == null || batchParameterList.isEmpty()) {
-   	     	return new int[0];
-    	}
-	   	try{
-	   		executeSql(new String[] {this.prepareSql}, true, ResultsMode.UPDATECOUNT);
-	   	}finally{
-	   		batchParameterList.clear();
-	   	}
-	   	return this.updateCounts;
-    }
-
-	@Override
-    public ResultSet executeQuery() throws SQLException {
-        executeSql(new String[] {this.prepareSql}, false, ResultsMode.RESULTSET);
-        return resultSet;
-    }
-
-	@Override
-    public int executeUpdate() throws SQLException {
-        executeSql(new String[] {this.prepareSql}, false, ResultsMode.UPDATECOUNT);
-        return this.updateCounts[0];
-    }
-    
-    @Override
-    protected RequestMessage createRequestMessage(String[] commands,
-    		boolean isBatchedCommand, ResultsMode resultsMode) {
-    	RequestMessage message = super.createRequestMessage(commands, false, resultsMode);
-    	message.setStatementType(StatementType.PREPARED);
-    	message.setParameterValues(isBatchedCommand?getParameterValuesList(): getParameterValues());
-    	message.setBatchedUpdate(isBatchedCommand);
-    	return message;
-    }
-
-    /**
-     * <p>Retreives a ResultSetMetaData object with information about the numbers,
-     * types, and properties of columns in the ResultSet object that will be returned
-     * when this preparedstatement object is executed.
-     * @return ResultSetMetaData object
-     * @throws SQLException, currently there is no means of getting results
-     * metadata before getting results.
-     */
-    public ResultSetMetaData getMetaData() throws SQLException {
-
-        // check if the statement is open
-        checkStatement();
-
-        if(metadata == null) {
-        	if (updateCounts != null) {
-        		return null;
-        	} else if(resultSet != null) {
-                metadata = resultSet.getMetaData();
-            } else {
-				if (getMetadataResults().getColumnMetadata() == null) {
-					return null;
-				}
-                MetadataProvider provider = new MetadataProvider(getMetadataResults().getColumnMetadata());
-                metadata = new ResultSetMetaDataImpl(provider);
-            }
-        }
-
-        return metadata;
-    }
-
-	private MetadataResult getMetadataResults() throws TeiidSQLException {
-		if (metadataResults == null) {
-			try {
-				metadataResults = this.getDQP().getMetadata(this.currentRequestID, prepareSql, Boolean.valueOf(getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS)).booleanValue());
-			} catch (TeiidComponentException e) {
-				throw TeiidSQLException.create(e);
-			} catch (TeiidProcessingException e) {
-				throw TeiidSQLException.create(e);
-			}
-		}
-		return metadataResults;
-	}
-
-    public void setAsciiStream(int parameterIndex, java.io.InputStream in, int length) throws SQLException {
-    	setAsciiStream(parameterIndex, in);
-    }
-
-    /**
-     * <p>Sets the IN parameter at paramaterIndex to a BigDecimal object. The parameter
-     * type is set to NUMERIC
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param BigDecimal object to which the parameter value is to be set.
-     * @throws SQLException, should not occur
-     */
-    public void setBigDecimal (int parameterIndex, java.math.BigDecimal value) throws SQLException {
-        setObject(parameterIndex, value);
-    }
-
-    public void setBinaryStream(int parameterIndex, java.io.InputStream in, int length) throws SQLException {
-    	setBlob(parameterIndex, in);
-    }
-
-    /**
-     * <p>Sets the parameter in position parameterIndex to a Blob object.
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param Blob object to which the parameter value is to be set.
-     * @throws SQLException if parameter type/datatype do not match
-     */
-    public void setBlob (int parameterIndex, Blob x) throws SQLException {
-        setObject(parameterIndex, x);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to b, a Java boolean value. The parameter
-     * type is set to BIT
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param boolean value to which the parameter value is to be set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setBoolean (int parameterIndex, boolean value) throws SQLException {
-        setObject(parameterIndex, value);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a Java byte value. The parameter
-     * type is set to TINYINT
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param byte value to which the parameter value is to be set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setByte(int parameterIndex, byte value) throws SQLException {
-        setObject(parameterIndex, Byte.valueOf(value));
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x[], a Java array of bytes.
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param bytes array to which the parameter value is to be set.
-     */
-    public void setBytes(int parameterIndex, byte bytes[]) throws SQLException {
-    	setObject(parameterIndex, new SerialBlob(bytes));
-    }
-
-    public void setCharacterStream (int parameterIndex, java.io.Reader reader, int length) throws SQLException {
-    	setCharacterStream(parameterIndex, reader);
-    }
-
-    /**
-     * <p>Sets the parameter in position parameterIndex to a Clob object.
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param Clob object to which the parameter value is to be set.
-     * @throws SQLException if parameter type/datatype do not match.
-     */
-    public void setClob (int parameterIndex, Clob x) throws SQLException {
-        setObject(parameterIndex, x);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a java.sql.Date object. The parameter
-     * type is set to DATE
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param Date object to which the parameter value is to be set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setDate(int parameterIndex, java.sql.Date value) throws SQLException {
-        setDate(parameterIndex, value, null);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a java.sql.Date object. The parameter
-     * type is set to DATE
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param Date object to which the parameter value is to be set.
-     * @param Calendar object to constrct date(useful to get include timezone info)
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setDate(int parameterIndex, java.sql.Date x ,java.util.Calendar cal) throws SQLException {
-
-        if (cal == null || x == null) {
-            setObject(parameterIndex, x);
-            return;
-        }
-                
-        // set the parameter on the stored procedure
-        setObject(parameterIndex, TimestampWithTimezone.createDate(x, cal.getTimeZone(), getDefaultCalendar()));
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a double value. The parameter
-     * type is set to DOUBLE
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param double value to which the parameter value is to be set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setDouble(int parameterIndex, double value) throws SQLException {
-        setObject(parameterIndex, new Double(value));
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to value, a float value. The parameter
-     * type is set to FLOAT
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param float value to which the parameter value is to be set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setFloat(int parameterIndex, float value) throws SQLException {
-        setObject(parameterIndex, new Float(value));
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to value, a int value. The parameter
-     * type is set to INTEGER
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param int value to which the parameter value is to be set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setInt(int parameterIndex, int value) throws SQLException {
-        setObject(parameterIndex, Integer.valueOf(value));
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a long value. The parameter
-     * type is set to BIGINT
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param long value to which the parameter value is to be set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setLong(int parameterIndex, long value) throws SQLException {
-        setObject(parameterIndex, Long.valueOf(value));
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to a null value.
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param jdbc type of the parameter whose value is to be set to null
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setNull(int parameterIndex, int jdbcType) throws SQLException {
-        setObject(parameterIndex, null);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to a null value.
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param jdbc type of the parameter whose value is to be set to null
-     * @param fully qualifies typename of the parameter being set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setNull(int parameterIndex, int jdbcType, String typeName) throws SQLException {
-        setObject(parameterIndex, null);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to an object value
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param an object value to which the parameter value is to be set.
-     * @param int value giving the JDBC type to conver the object to
-     * @param int value giving the scale to be set if the type is DECIMAL or NUMERIC
-     * @throws SQLException, if there is an error setting the parameter value
-     */
-    public void setObject (int parameterIndex, Object value, int targetJdbcType, int scale) throws SQLException {
-
-       if(value == null) {
-            setObject(parameterIndex, null);
-            return;
-        }
-
-       if(targetJdbcType != Types.DECIMAL || targetJdbcType != Types.NUMERIC) {
-            setObject(parameterIndex, value, targetJdbcType);
-        // Decimal and NUMERIC types correspong to java.math.BigDecimal
-        } else {
-            // transform the object to a BigDecimal
-            BigDecimal bigDecimalObject = DataTypeTransformer.getBigDecimal(value);
-            // set scale on the BigDecimal
-            setObject(parameterIndex, bigDecimalObject.setScale(scale));
-        }
-    }
-    
-    public void setObject(int parameterIndex, Object value, int targetJdbcType) throws SQLException {
-
-        Object targetObject = null;
-
-       if(value == null) {
-            setObject(parameterIndex, null);
-            return;
-        }
-
-        // get the java class name for the given JDBC type
-        String javaClassName = JDBCSQLTypeInfo.getJavaClassName(targetJdbcType);
-        // transform the value to the target datatype
-        if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.STRING_CLASS)) {
-           targetObject = value.toString();
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.CHAR_CLASS)) {
-            targetObject = DataTypeTransformer.getCharacter(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.INTEGER_CLASS)) {
-            targetObject = DataTypeTransformer.getInteger(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.BYTE_CLASS)) {
-            targetObject = DataTypeTransformer.getByte(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.SHORT_CLASS)) {
-            targetObject = DataTypeTransformer.getShort(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.LONG_CLASS)) {
-            targetObject = DataTypeTransformer.getLong(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.FLOAT_CLASS)) {
-            targetObject = DataTypeTransformer.getFloat(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.DOUBLE_CLASS)) {
-            targetObject = DataTypeTransformer.getDouble(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.BOOLEAN_CLASS)) {
-            targetObject = DataTypeTransformer.getBoolean(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.BIGDECIMAL_CLASS)) {
-            targetObject = DataTypeTransformer.getBigDecimal(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.TIMESTAMP_CLASS)) {
-            targetObject = DataTypeTransformer.getTimestamp(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.DATE_CLASS)) {
-            targetObject = DataTypeTransformer.getDate(value);
-        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.TIME_CLASS)) {
-            targetObject = DataTypeTransformer.getTime(value);
-        } else if (javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.BLOB_CLASS)) {
-            targetObject = DataTypeTransformer.getBlob(value);
-        } else if (javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.CLOB_CLASS)) {
-            targetObject = DataTypeTransformer.getClob(value);
-        } else {
-            String msg = JDBCPlugin.Util.getString("MMPreparedStatement.Err_transform_obj"); //$NON-NLS-1$
-            throw new TeiidSQLException(msg);
-        }
-
-        setObject(parameterIndex, targetObject);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to an object value
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param an object value to which the parameter value is to be set.
-     * @throws SQLException, if there is an error setting the parameter value
-     */
-    public void setObject(int parameterIndex, Object value) throws SQLException {
-        ArgCheck.isPositive(parameterIndex, JDBCPlugin.Util.getString("MMPreparedStatement.Invalid_param_index")); //$NON-NLS-1$
-
-        if(parameterMap == null){
-            parameterMap = new TreeMap<Integer, Object>();
-        }
-        
-        if (serverCalendar != null && value instanceof java.util.Date) {
-            value = TimestampWithTimezone.create((java.util.Date)value, getDefaultCalendar().getTimeZone(), serverCalendar, value.getClass());
-        }
-        parameterMap.put(parameterIndex, value);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a short value. The parameter
-     * type is set to TINYINT
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param short value to which the parameter value is to be set.
-     * @throws SQLException, if there is an error setting the parameter value
-     */
-    public void setShort(int parameterIndex, short value) throws SQLException {
-        setObject(parameterIndex, value);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a String value. The parameter
-     * type is set to VARCHAR
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param String object to which the parameter value is to be set.
-     * @throws SQLException
-     */
-    public void setString(int parameterIndex, String value) throws SQLException {
-        setObject(parameterIndex, value);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a java.sql.Time object. The parameter
-     * type is set to TIME
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param Time object to which the parameter value is to be set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setTime(int parameterIndex, java.sql.Time value) throws SQLException {
-        setTime(parameterIndex, value, null);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a java.sql.Time object. The parameter
-     * type is set to TIME
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param Time object to which the parameter value is to be set.
-     * @param Calendar object to constrct Time(useful to get include timezone info)
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setTime(int parameterIndex, java.sql.Time x, java.util.Calendar cal) throws SQLException {
-
-       if (cal == null || x == null) {
-           setObject(parameterIndex, x);
-           return;
-       }
-               
-       // set the parameter on the stored procedure
-       setObject(parameterIndex, TimestampWithTimezone.createTime(x, cal.getTimeZone(), getDefaultCalendar()));
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a java.sql.Timestamp object. The
-     * parameter type is set to TIMESTAMP
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param Timestamp object to which the parameter value is to be set.
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setTimestamp(int parameterIndex, java.sql.Timestamp value) throws SQLException {
-        setTimestamp(parameterIndex, value, null);
-    }
-
-    /**
-     * <p>Sets parameter number parameterIndex to x, a java.sql.Timestamp object. The
-     * parameter type is set to TIMESTAMP
-     * @param parameterIndex of the parameter whose value is to be set
-     * @param Timestamp object to which the parameter value is to be set.
-     * @param Calendar object to constrct timestamp(useful to get include timezone info)
-     * @throws SQLException, if parameter type/datatype do not match
-     */
-    public void setTimestamp(int parameterIndex, java.sql.Timestamp x, java.util.Calendar cal) throws SQLException {
-
-        if (cal == null || x == null) {
-            setObject(parameterIndex, x);
-            return;
-        }
-                
-        // set the parameter on the stored procedure
-        setObject(parameterIndex, TimestampWithTimezone.createTimestamp(x, cal.getTimeZone(), getDefaultCalendar()));
-    }
-
-    /**
-     * Sets the designated parameter to the given java.net.URL value. The driver
-     * converts this to an SQL DATALINK value when it sends it to the database.
-     * @param parameter int index
-     * @param x URL to be set
-     * @throws SQLException
-     */
-    public void setURL(int parameterIndex, URL x) throws SQLException {
-        setObject(parameterIndex, x);
-    }
-
-    List<List<Object>> getParameterValuesList() {
-    	if(batchParameterList == null || batchParameterList.isEmpty()){
-    		return Collections.emptyList();
-    	}
-    	return new ArrayList<List<Object>>(batchParameterList);
-    }
-    
-    List<Object> getParameterValues() {
-        if(parameterMap == null || parameterMap.isEmpty()){
-            return Collections.emptyList();
-        }
-        return new ArrayList<Object>(parameterMap.values());
-    }
-
-	public ParameterMetaData getParameterMetaData() throws SQLException {
-		if (parameterMetaData == null) {
-			//TODO: some of the base implementation of ResultSetMetadata could be on the MetadataProvider
-			this.parameterMetaData = new ParameterMetaDataImpl(new ResultSetMetaDataImpl(new MetadataProvider(getMetadataResults().getParameterMetadata())));
-		}
-		return parameterMetaData;
-	}
-
-    /**
-     * Exposed for unit testing 
-     */
-    void setServerCalendar(Calendar serverCalendar) {
-        this.serverCalendar = serverCalendar;
-    }
-
-	public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
-		setObject(parameterIndex, xmlObject);
-	}
-
-	public void setArray(int parameterIndex, Array x) throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-
-	public void setAsciiStream(int parameterIndex, final InputStream x)
-			throws SQLException {
-		this.setObject(parameterIndex, new ClobImpl(new InputStreamFactory() { 
-			@Override
-			public InputStream getInputStream() throws IOException {
-				return x;
-			}
-		}, -1));
-	}
-
-	public void setAsciiStream(int parameterIndex, InputStream x, long length)
-			throws SQLException {
-		setAsciiStream(parameterIndex, x);
-	}
-
-	public void setBinaryStream(int parameterIndex, InputStream x)
-			throws SQLException {
-		setBlob(parameterIndex, x);
-	}
-
-	public void setBinaryStream(int parameterIndex, InputStream x, long length)
-			throws SQLException {
-		setBinaryStream(parameterIndex, x);
-	}
-
-	public void setBlob(int parameterIndex, final InputStream inputStream)
-			throws SQLException {
-		this.setObject(parameterIndex, new BlobImpl(new InputStreamFactory() {
-			@Override
-			public InputStream getInputStream() throws IOException {
-				return inputStream;
-			}
-		}));
-	}
-
-	public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
-		setBlob(parameterIndex, inputStream);
-	}
-
-	public void setCharacterStream(int parameterIndex, Reader reader)
-			throws SQLException {
-		setClob(parameterIndex, reader);
-	}
-
-	public void setCharacterStream(int parameterIndex, Reader reader,
-			long length) throws SQLException {
-		setCharacterStream(parameterIndex, reader);
-	}
-
-	public void setClob(int parameterIndex, final Reader reader) throws SQLException {
-		this.setObject(parameterIndex, new ClobImpl(new InputStreamFactory() {
-			
-			@Override
-			public InputStream getInputStream() throws IOException {
-				return new ReaderInputStream(reader, Charset.forName(Streamable.ENCODING));
-			}
-		}, -1));
-	}
-
-	public void setClob(int parameterIndex, Reader reader, long length)
-			throws SQLException {
-		setClob(parameterIndex, reader);
-	}
-
-	public void setNCharacterStream(int parameterIndex, Reader value)
-			throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-
-	public void setNCharacterStream(int parameterIndex, Reader value,
-			long length) throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-
-	public void setNClob(int parameterIndex, NClob value) throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-
-	public void setNClob(int parameterIndex, Reader reader) throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-
-	public void setNClob(int parameterIndex, Reader reader, long length)
-			throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-
-	public void setNString(int parameterIndex, String value)
-			throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-
-	public void setRef(int parameterIndex, Ref x) throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-
-	public void setRowId(int parameterIndex, RowId x) throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-
-	public void setUnicodeStream(int parameterIndex, InputStream x, int length)
-			throws SQLException {
-		throw SqlUtil.createFeatureNotSupportedException();
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java (from rev 2802, trunk/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,783 @@
+/*
+ * 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.jdbc;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.math.BigDecimal;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.NClob;
+import java.sql.ParameterMetaData;
+import java.sql.PreparedStatement;
+import java.sql.Ref;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.RowId;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.TimeZone;
+import java.util.TreeMap;
+
+import javax.sql.rowset.serial.SerialBlob;
+
+import org.teiid.client.RequestMessage;
+import org.teiid.client.RequestMessage.ResultsMode;
+import org.teiid.client.RequestMessage.StatementType;
+import org.teiid.client.metadata.MetadataResult;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.BlobImpl;
+import org.teiid.core.types.ClobImpl;
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.JDBCSQLTypeInfo;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.util.ArgCheck;
+import org.teiid.core.util.ReaderInputStream;
+import org.teiid.core.util.SqlUtil;
+import org.teiid.core.util.TimestampWithTimezone;
+
+
+/**
+ * <p> Instances of PreparedStatement contain a SQL statement that has already been
+ * compiled.  The SQL statement contained in a PreparedStatement object may have
+ * one or more IN parameters. An IN parameter is a parameter whose value is not
+ * specified when a SQL statement is created. Instead the statement has a placeholder
+ * for each IN parameter.</p>
+ * <p> The MMPreparedStatement object wraps the server's PreparedStatement object.
+ * The methods in this class are used to set the IN parameters on a server's
+ * preparedstatement object.</p>
+ */
+
+public class PreparedStatementImpl extends StatementImpl implements PreparedStatement {
+    // sql, which this prepared statement is operating on
+    protected String prepareSql;
+
+    //map that holds parameter index to values for prepared statements
+    private Map<Integer, Object> parameterMap;
+    
+    //a list of map that holds parameter index to values for prepared statements
+    protected List<List<Object>> batchParameterList;
+
+    // metadata
+	private MetadataResult metadataResults;
+    private ResultSetMetaData metadata;
+    private ParameterMetaData parameterMetaData;
+    
+    private Calendar serverCalendar;
+
+    /**
+     * Factory Constructor 
+     * @param connection
+     * @param sql
+     * @param resultSetType
+     * @param resultSetConcurrency
+     */
+    static PreparedStatementImpl newInstance(ConnectionImpl connection, String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
+        return new PreparedStatementImpl(connection, sql, resultSetType, resultSetConcurrency);        
+    }
+    
+    /**
+     * <p>MMPreparedStatement constructor.
+     * @param Driver's connection object.
+     * @param String object representing the prepared statement
+     */
+    PreparedStatementImpl(ConnectionImpl connection, String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
+        super(connection, resultSetType, resultSetConcurrency);
+
+        // this sql is for callable statement, don't check any more
+        ArgCheck.isNotNull(sql, JDBCPlugin.Util.getString("MMPreparedStatement.Err_prep_sql")); //$NON-NLS-1$
+        this.prepareSql = sql;
+
+        TimeZone timezone = connection.getServerConnection().getLogonResult().getTimeZone();
+
+        if (timezone != null && !timezone.hasSameRules(getDefaultCalendar().getTimeZone())) {
+        	this.serverCalendar = Calendar.getInstance(timezone);
+        }        
+    }
+
+    /**
+     * <p>Adds a set of parameters to this PreparedStatement object's list of commands
+     * to be sent to the database for execution as a batch.
+     * @throws SQLException if there is an error
+     */
+    public void addBatch() throws SQLException {
+        checkStatement();
+    	if(batchParameterList == null){
+    		batchParameterList = new ArrayList<List<Object>>();
+		}
+    	batchParameterList.add(getParameterValues());
+		clearParameters();
+    }
+
+    /**
+     * Makes the set of commands in the current batch empty.
+     *
+     * @throws SQLException if a database access error occurs or the
+     * driver does not support batch statements
+     */
+    public void clearBatch() throws SQLException {
+    	if (batchParameterList != null ) {
+    		batchParameterList.clear();
+    	}
+    }
+
+    /**
+     * <p>Clears the values set for the PreparedStatement object's IN parameters and
+     * releases the resources used by those values. In general, parameter values
+     * remain in force for repeated use of statement.
+     * @throws SQLException if there is an error while clearing params
+     */
+    public void clearParameters() throws SQLException {
+        checkStatement();
+        //clear the parameters list on servers prepared statement object
+        if(parameterMap != null){
+            parameterMap.clear();
+        }
+    }
+    
+    @Override
+    public boolean execute(String sql) throws SQLException {
+    	String msg = JDBCPlugin.Util.getString("JDBC.Method_not_supported"); //$NON-NLS-1$
+        throw new TeiidSQLException(msg);
+    }
+    
+    @Override
+    public ResultSet executeQuery(String sql) throws SQLException {
+    	String msg = JDBCPlugin.Util.getString("JDBC.Method_not_supported"); //$NON-NLS-1$
+        throw new TeiidSQLException(msg);
+    }
+    
+    @Override
+    public int executeUpdate(String sql) throws SQLException {
+    	String msg = JDBCPlugin.Util.getString("JDBC.Method_not_supported"); //$NON-NLS-1$
+        throw new TeiidSQLException(msg);
+    }
+    
+    @Override
+    public void addBatch(String sql) throws SQLException {
+    	String msg = JDBCPlugin.Util.getString("JDBC.Method_not_supported"); //$NON-NLS-1$
+        throw new TeiidSQLException(msg);
+    }
+
+	@Override
+    public boolean execute() throws SQLException {
+        executeSql(new String[] {this.prepareSql}, false, ResultsMode.EITHER);
+        return hasResultSet();
+    }
+    
+    @Override
+    public int[] executeBatch() throws SQLException {
+    	if (batchParameterList == null || batchParameterList.isEmpty()) {
+   	     	return new int[0];
+    	}
+	   	try{
+	   		executeSql(new String[] {this.prepareSql}, true, ResultsMode.UPDATECOUNT);
+	   	}finally{
+	   		batchParameterList.clear();
+	   	}
+	   	return this.updateCounts;
+    }
+
+	@Override
+    public ResultSet executeQuery() throws SQLException {
+        executeSql(new String[] {this.prepareSql}, false, ResultsMode.RESULTSET);
+        return resultSet;
+    }
+
+	@Override
+    public int executeUpdate() throws SQLException {
+        executeSql(new String[] {this.prepareSql}, false, ResultsMode.UPDATECOUNT);
+        return this.updateCounts[0];
+    }
+    
+    @Override
+    protected RequestMessage createRequestMessage(String[] commands,
+    		boolean isBatchedCommand, ResultsMode resultsMode) {
+    	RequestMessage message = super.createRequestMessage(commands, false, resultsMode);
+    	message.setStatementType(StatementType.PREPARED);
+    	message.setParameterValues(isBatchedCommand?getParameterValuesList(): getParameterValues());
+    	message.setBatchedUpdate(isBatchedCommand);
+    	return message;
+    }
+
+    /**
+     * <p>Retreives a ResultSetMetaData object with information about the numbers,
+     * types, and properties of columns in the ResultSet object that will be returned
+     * when this preparedstatement object is executed.
+     * @return ResultSetMetaData object
+     * @throws SQLException, currently there is no means of getting results
+     * metadata before getting results.
+     */
+    public ResultSetMetaData getMetaData() throws SQLException {
+
+        // check if the statement is open
+        checkStatement();
+
+        if(metadata == null) {
+        	if (updateCounts != null) {
+        		return null;
+        	} else if(resultSet != null) {
+                metadata = resultSet.getMetaData();
+            } else {
+				if (getMetadataResults().getColumnMetadata() == null) {
+					return null;
+				}
+                MetadataProvider provider = new MetadataProvider(getMetadataResults().getColumnMetadata());
+                metadata = new ResultSetMetaDataImpl(provider);
+            }
+        }
+
+        return metadata;
+    }
+
+	private MetadataResult getMetadataResults() throws TeiidSQLException {
+		if (metadataResults == null) {
+			try {
+				metadataResults = this.getDQP().getMetadata(this.currentRequestID, prepareSql, Boolean.valueOf(getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS)).booleanValue());
+			} catch (TeiidComponentException e) {
+				throw TeiidSQLException.create(e);
+			} catch (TeiidProcessingException e) {
+				throw TeiidSQLException.create(e);
+			}
+		}
+		return metadataResults;
+	}
+
+    public void setAsciiStream(int parameterIndex, java.io.InputStream in, int length) throws SQLException {
+    	setAsciiStream(parameterIndex, in);
+    }
+
+    /**
+     * <p>Sets the IN parameter at paramaterIndex to a BigDecimal object. The parameter
+     * type is set to NUMERIC
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param BigDecimal object to which the parameter value is to be set.
+     * @throws SQLException, should not occur
+     */
+    public void setBigDecimal (int parameterIndex, java.math.BigDecimal value) throws SQLException {
+        setObject(parameterIndex, value);
+    }
+
+    public void setBinaryStream(int parameterIndex, java.io.InputStream in, int length) throws SQLException {
+    	setBlob(parameterIndex, in);
+    }
+
+    /**
+     * <p>Sets the parameter in position parameterIndex to a Blob object.
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param Blob object to which the parameter value is to be set.
+     * @throws SQLException if parameter type/datatype do not match
+     */
+    public void setBlob (int parameterIndex, Blob x) throws SQLException {
+        setObject(parameterIndex, x);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to b, a Java boolean value. The parameter
+     * type is set to BIT
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param boolean value to which the parameter value is to be set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setBoolean (int parameterIndex, boolean value) throws SQLException {
+        setObject(parameterIndex, value);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a Java byte value. The parameter
+     * type is set to TINYINT
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param byte value to which the parameter value is to be set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setByte(int parameterIndex, byte value) throws SQLException {
+        setObject(parameterIndex, Byte.valueOf(value));
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x[], a Java array of bytes.
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param bytes array to which the parameter value is to be set.
+     */
+    public void setBytes(int parameterIndex, byte bytes[]) throws SQLException {
+    	setObject(parameterIndex, new SerialBlob(bytes));
+    }
+
+    public void setCharacterStream (int parameterIndex, java.io.Reader reader, int length) throws SQLException {
+    	setCharacterStream(parameterIndex, reader);
+    }
+
+    /**
+     * <p>Sets the parameter in position parameterIndex to a Clob object.
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param Clob object to which the parameter value is to be set.
+     * @throws SQLException if parameter type/datatype do not match.
+     */
+    public void setClob (int parameterIndex, Clob x) throws SQLException {
+        setObject(parameterIndex, x);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a java.sql.Date object. The parameter
+     * type is set to DATE
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param Date object to which the parameter value is to be set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setDate(int parameterIndex, java.sql.Date value) throws SQLException {
+        setDate(parameterIndex, value, null);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a java.sql.Date object. The parameter
+     * type is set to DATE
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param Date object to which the parameter value is to be set.
+     * @param Calendar object to constrct date(useful to get include timezone info)
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setDate(int parameterIndex, java.sql.Date x ,java.util.Calendar cal) throws SQLException {
+
+        if (cal == null || x == null) {
+            setObject(parameterIndex, x);
+            return;
+        }
+                
+        // set the parameter on the stored procedure
+        setObject(parameterIndex, TimestampWithTimezone.createDate(x, cal.getTimeZone(), getDefaultCalendar()));
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a double value. The parameter
+     * type is set to DOUBLE
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param double value to which the parameter value is to be set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setDouble(int parameterIndex, double value) throws SQLException {
+        setObject(parameterIndex, new Double(value));
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to value, a float value. The parameter
+     * type is set to FLOAT
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param float value to which the parameter value is to be set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setFloat(int parameterIndex, float value) throws SQLException {
+        setObject(parameterIndex, new Float(value));
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to value, a int value. The parameter
+     * type is set to INTEGER
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param int value to which the parameter value is to be set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setInt(int parameterIndex, int value) throws SQLException {
+        setObject(parameterIndex, Integer.valueOf(value));
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a long value. The parameter
+     * type is set to BIGINT
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param long value to which the parameter value is to be set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setLong(int parameterIndex, long value) throws SQLException {
+        setObject(parameterIndex, Long.valueOf(value));
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to a null value.
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param jdbc type of the parameter whose value is to be set to null
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setNull(int parameterIndex, int jdbcType) throws SQLException {
+        setObject(parameterIndex, null);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to a null value.
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param jdbc type of the parameter whose value is to be set to null
+     * @param fully qualifies typename of the parameter being set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setNull(int parameterIndex, int jdbcType, String typeName) throws SQLException {
+        setObject(parameterIndex, null);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to an object value
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param an object value to which the parameter value is to be set.
+     * @param int value giving the JDBC type to conver the object to
+     * @param int value giving the scale to be set if the type is DECIMAL or NUMERIC
+     * @throws SQLException, if there is an error setting the parameter value
+     */
+    public void setObject (int parameterIndex, Object value, int targetJdbcType, int scale) throws SQLException {
+
+       if(value == null) {
+            setObject(parameterIndex, null);
+            return;
+        }
+
+       if(targetJdbcType != Types.DECIMAL || targetJdbcType != Types.NUMERIC) {
+            setObject(parameterIndex, value, targetJdbcType);
+        // Decimal and NUMERIC types correspong to java.math.BigDecimal
+        } else {
+            // transform the object to a BigDecimal
+            BigDecimal bigDecimalObject = DataTypeTransformer.getBigDecimal(value);
+            // set scale on the BigDecimal
+            setObject(parameterIndex, bigDecimalObject.setScale(scale));
+        }
+    }
+    
+    public void setObject(int parameterIndex, Object value, int targetJdbcType) throws SQLException {
+
+        Object targetObject = null;
+
+       if(value == null) {
+            setObject(parameterIndex, null);
+            return;
+        }
+
+        // get the java class name for the given JDBC type
+        String javaClassName = JDBCSQLTypeInfo.getJavaClassName(targetJdbcType);
+        // transform the value to the target datatype
+        if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.STRING_CLASS)) {
+           targetObject = value.toString();
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.CHAR_CLASS)) {
+            targetObject = DataTypeTransformer.getCharacter(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.INTEGER_CLASS)) {
+            targetObject = DataTypeTransformer.getInteger(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.BYTE_CLASS)) {
+            targetObject = DataTypeTransformer.getByte(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.SHORT_CLASS)) {
+            targetObject = DataTypeTransformer.getShort(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.LONG_CLASS)) {
+            targetObject = DataTypeTransformer.getLong(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.FLOAT_CLASS)) {
+            targetObject = DataTypeTransformer.getFloat(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.DOUBLE_CLASS)) {
+            targetObject = DataTypeTransformer.getDouble(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.BOOLEAN_CLASS)) {
+            targetObject = DataTypeTransformer.getBoolean(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.BIGDECIMAL_CLASS)) {
+            targetObject = DataTypeTransformer.getBigDecimal(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.TIMESTAMP_CLASS)) {
+            targetObject = DataTypeTransformer.getTimestamp(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.DATE_CLASS)) {
+            targetObject = DataTypeTransformer.getDate(value);
+        } else if(javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.TIME_CLASS)) {
+            targetObject = DataTypeTransformer.getTime(value);
+        } else if (javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.BLOB_CLASS)) {
+            targetObject = DataTypeTransformer.getBlob(value);
+        } else if (javaClassName.equalsIgnoreCase(JDBCSQLTypeInfo.CLOB_CLASS)) {
+            targetObject = DataTypeTransformer.getClob(value);
+        } else {
+            String msg = JDBCPlugin.Util.getString("MMPreparedStatement.Err_transform_obj"); //$NON-NLS-1$
+            throw new TeiidSQLException(msg);
+        }
+
+        setObject(parameterIndex, targetObject);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to an object value
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param an object value to which the parameter value is to be set.
+     * @throws SQLException, if there is an error setting the parameter value
+     */
+    public void setObject(int parameterIndex, Object value) throws SQLException {
+        ArgCheck.isPositive(parameterIndex, JDBCPlugin.Util.getString("MMPreparedStatement.Invalid_param_index")); //$NON-NLS-1$
+
+        if(parameterMap == null){
+            parameterMap = new TreeMap<Integer, Object>();
+        }
+        
+        if (serverCalendar != null && value instanceof java.util.Date) {
+            value = TimestampWithTimezone.create((java.util.Date)value, getDefaultCalendar().getTimeZone(), serverCalendar, value.getClass());
+        }
+        parameterMap.put(parameterIndex, value);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a short value. The parameter
+     * type is set to TINYINT
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param short value to which the parameter value is to be set.
+     * @throws SQLException, if there is an error setting the parameter value
+     */
+    public void setShort(int parameterIndex, short value) throws SQLException {
+        setObject(parameterIndex, value);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a String value. The parameter
+     * type is set to VARCHAR
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param String object to which the parameter value is to be set.
+     * @throws SQLException
+     */
+    public void setString(int parameterIndex, String value) throws SQLException {
+        setObject(parameterIndex, value);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a java.sql.Time object. The parameter
+     * type is set to TIME
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param Time object to which the parameter value is to be set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setTime(int parameterIndex, java.sql.Time value) throws SQLException {
+        setTime(parameterIndex, value, null);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a java.sql.Time object. The parameter
+     * type is set to TIME
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param Time object to which the parameter value is to be set.
+     * @param Calendar object to constrct Time(useful to get include timezone info)
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setTime(int parameterIndex, java.sql.Time x, java.util.Calendar cal) throws SQLException {
+
+       if (cal == null || x == null) {
+           setObject(parameterIndex, x);
+           return;
+       }
+               
+       // set the parameter on the stored procedure
+       setObject(parameterIndex, TimestampWithTimezone.createTime(x, cal.getTimeZone(), getDefaultCalendar()));
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a java.sql.Timestamp object. The
+     * parameter type is set to TIMESTAMP
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param Timestamp object to which the parameter value is to be set.
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setTimestamp(int parameterIndex, java.sql.Timestamp value) throws SQLException {
+        setTimestamp(parameterIndex, value, null);
+    }
+
+    /**
+     * <p>Sets parameter number parameterIndex to x, a java.sql.Timestamp object. The
+     * parameter type is set to TIMESTAMP
+     * @param parameterIndex of the parameter whose value is to be set
+     * @param Timestamp object to which the parameter value is to be set.
+     * @param Calendar object to constrct timestamp(useful to get include timezone info)
+     * @throws SQLException, if parameter type/datatype do not match
+     */
+    public void setTimestamp(int parameterIndex, java.sql.Timestamp x, java.util.Calendar cal) throws SQLException {
+
+        if (cal == null || x == null) {
+            setObject(parameterIndex, x);
+            return;
+        }
+                
+        // set the parameter on the stored procedure
+        setObject(parameterIndex, TimestampWithTimezone.createTimestamp(x, cal.getTimeZone(), getDefaultCalendar()));
+    }
+
+    /**
+     * Sets the designated parameter to the given java.net.URL value. The driver
+     * converts this to an SQL DATALINK value when it sends it to the database.
+     * @param parameter int index
+     * @param x URL to be set
+     * @throws SQLException
+     */
+    public void setURL(int parameterIndex, URL x) throws SQLException {
+        setObject(parameterIndex, x);
+    }
+
+    List<List<Object>> getParameterValuesList() {
+    	if(batchParameterList == null || batchParameterList.isEmpty()){
+    		return Collections.emptyList();
+    	}
+    	return new ArrayList<List<Object>>(batchParameterList);
+    }
+    
+    List<Object> getParameterValues() {
+        if(parameterMap == null || parameterMap.isEmpty()){
+            return Collections.emptyList();
+        }
+        return new ArrayList<Object>(parameterMap.values());
+    }
+
+	public ParameterMetaData getParameterMetaData() throws SQLException {
+		if (parameterMetaData == null) {
+			//TODO: some of the base implementation of ResultSetMetadata could be on the MetadataProvider
+			this.parameterMetaData = new ParameterMetaDataImpl(new ResultSetMetaDataImpl(new MetadataProvider(getMetadataResults().getParameterMetadata())));
+		}
+		return parameterMetaData;
+	}
+
+    /**
+     * Exposed for unit testing 
+     */
+    void setServerCalendar(Calendar serverCalendar) {
+        this.serverCalendar = serverCalendar;
+    }
+
+	public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
+		setObject(parameterIndex, xmlObject);
+	}
+
+	public void setArray(int parameterIndex, Array x) throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+
+	public void setAsciiStream(int parameterIndex, final InputStream x)
+			throws SQLException {
+		this.setObject(parameterIndex, new ClobImpl(new InputStreamFactory() { 
+			@Override
+			public InputStream getInputStream() throws IOException {
+				return x;
+			}
+		}, -1));
+	}
+
+	public void setAsciiStream(int parameterIndex, InputStream x, long length)
+			throws SQLException {
+		setAsciiStream(parameterIndex, x);
+	}
+
+	public void setBinaryStream(int parameterIndex, InputStream x)
+			throws SQLException {
+		setBlob(parameterIndex, x);
+	}
+
+	public void setBinaryStream(int parameterIndex, InputStream x, long length)
+			throws SQLException {
+		setBinaryStream(parameterIndex, x);
+	}
+
+	public void setBlob(int parameterIndex, final InputStream inputStream)
+			throws SQLException {
+		if (inputStream == null) {
+			this.setObject(parameterIndex, null);
+			return;
+		}
+		this.setObject(parameterIndex, new BlobImpl(new InputStreamFactory() {
+			@Override
+			public InputStream getInputStream() throws IOException {
+				return inputStream;
+			}
+		}));
+	}
+
+	public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
+		setBlob(parameterIndex, inputStream);
+	}
+
+	public void setCharacterStream(int parameterIndex, Reader reader)
+			throws SQLException {
+		setClob(parameterIndex, reader);
+	}
+
+	public void setCharacterStream(int parameterIndex, Reader reader,
+			long length) throws SQLException {
+		setCharacterStream(parameterIndex, reader);
+	}
+
+	public void setClob(int parameterIndex, final Reader reader) throws SQLException {
+		if (reader == null) {
+			this.setObject(parameterIndex, null);
+			return;
+		}
+		this.setObject(parameterIndex, new ClobImpl(new InputStreamFactory() {
+			
+			@Override
+			public InputStream getInputStream() throws IOException {
+				return new ReaderInputStream(reader, Charset.forName(Streamable.ENCODING));
+			}
+		}, -1));
+	}
+
+	public void setClob(int parameterIndex, Reader reader, long length)
+			throws SQLException {
+		setClob(parameterIndex, reader);
+	}
+
+	public void setNCharacterStream(int parameterIndex, Reader value)
+			throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+
+	public void setNCharacterStream(int parameterIndex, Reader value,
+			long length) throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+
+	public void setNClob(int parameterIndex, NClob value) throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+
+	public void setNClob(int parameterIndex, Reader reader) throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+
+	public void setNClob(int parameterIndex, Reader reader, long length)
+			throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+
+	public void setNString(int parameterIndex, String value)
+			throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+
+	public void setRef(int parameterIndex, Ref x) throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+
+	public void setRowId(int parameterIndex, RowId x) throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+
+	public void setUnicodeStream(int parameterIndex, InputStream x, int length)
+			throws SQLException {
+		throw SqlUtil.createFeatureNotSupportedException();
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java
===================================================================
--- trunk/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,364 +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.net.socket;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.teiid.client.security.ILogon;
-import org.teiid.client.security.InvalidSessionException;
-import org.teiid.client.security.SessionToken;
-import org.teiid.core.TeiidException;
-import org.teiid.core.util.PropertiesUtils;
-import org.teiid.core.util.ReflectionHelper;
-import org.teiid.net.CommunicationException;
-import org.teiid.net.ConnectionException;
-import org.teiid.net.HostInfo;
-import org.teiid.net.ServerConnection;
-import org.teiid.net.ServerConnectionFactory;
-import org.teiid.net.TeiidURL;
-
-
-/**
- * Responsible for creating socket based connections
- * 
- * The comm approach is object based and layered.  Connections manage failover and identity.  
- * ServerInstances represent the service layer to a particular cluster member.  ObjectChannels
- * abstract the underlying IO.
- * 
- */
-public class SocketServerConnectionFactory implements ServerConnectionFactory, SocketServerInstanceFactory {
-
-	private static final String URL = "URL"; //$NON-NLS-1$
-	
-	private static SocketServerConnectionFactory INSTANCE;
-	private static Logger log = Logger.getLogger("org.teiid.client.sockets"); //$NON-NLS-1$
-
-	private final class ShutdownHandler implements InvocationHandler {
-		private final CachedInstance key;
-
-		private ShutdownHandler(CachedInstance key) {
-			this.key = key;
-		}
-
-		@Override
-		public Object invoke(Object arg0, Method arg1, Object[] arg2)
-				throws Throwable {
-			if (arg1.getName().equals("shutdown")) { //$NON-NLS-1$
-				CachedInstance purge = null;
-				if (!key.actual.isOpen()) {
-					return null; //nothing to do
-				}
-				synchronized (instancePool) {
-					instancePool.put(key, key);
-					if (instancePool.size() > maxCachedInstances) {
-						Iterator<CachedInstance> iter = instancePool.keySet().iterator();
-						purge = iter.next();
-						iter.remove();
-					}
-				}
-				if (purge != null) {
-					purge.actual.shutdown();
-				}
-				return null;
-			}
-			try {
-				return arg1.invoke(key.actual, arg2);
-			} catch (InvocationTargetException e) {
-				throw e.getTargetException();
-			}
-		}
-	}
-
-	private static class CachedInstance {
-		HostInfo info;
-		Integer instance;
-		SocketServerInstance actual;
-		SocketServerInstance proxy;
-		
-		public CachedInstance(HostInfo info) {
-			this.info = info;
-		}
-
-		@Override
-		public int hashCode() {
-			return info.hashCode();
-		}
-		
-		@Override
-		public boolean equals(Object obj) {
-			if (this == obj) {
-				return true;
-			}
-			if (!(obj instanceof CachedInstance)) {
-				return false;
-			}
-			CachedInstance other = (CachedInstance) obj;
-			if (!info.equals(other.info)) {
-				return false;
-			}
-			if (instance == null || other.instance == null) {
-				return true;
-			} 
-			return instance.equals(other.instance);
-		}
-	}
-	
-    private ObjectChannelFactory channelFactory;
-	private Timer pingTimer;
-	
-	private HashMap<HostInfo, Set<SessionToken>> sessions = new HashMap<HostInfo, Set<SessionToken>>();
-	
-	//instance pooling
-	private AtomicInteger instanceCount = new AtomicInteger();
-	private Map<CachedInstance, CachedInstance> instancePool = new LinkedHashMap<CachedInstance, CachedInstance>();
-
-	//config properties
-	private long synchronousTtl = 120000l;
-	private int maxCachedInstances=16;
-
-	public static synchronized SocketServerConnectionFactory getInstance() {
-		if (INSTANCE == null) {
-			INSTANCE = new SocketServerConnectionFactory();
-			Properties props = System.getProperties();
-			InputStream is = SocketServerConnectionFactory.class.getResourceAsStream("/teiid-client-settings.properties"); //$NON-NLS-1$
-			if (is != null) {
-				props = new Properties(props);
-				try {
-					props.load(is);
-				} catch (IOException e) {
-					
-				} finally {
-					try {
-						is.close();
-					} catch (IOException e) {
-					}
-				}
-			}
-			INSTANCE.initialize(props);
-		}
-		return INSTANCE;
-	}
-	
-	public SocketServerConnectionFactory() {
-		
-	}
-	
-	public void initialize(Properties info) {
-		PropertiesUtils.setBeanProperties(this, info, "org.teiid.sockets"); //$NON-NLS-1$
-		this.pingTimer = new Timer("SocketPing", true); //$NON-NLS-1$
-		this.pingTimer.schedule(new TimerTask() {
-			
-			@Override
-			public void run() {
-				Set<Map.Entry<HostInfo, Set<SessionToken>>> sessionEntries = null;
-				synchronized (sessions) {
-					sessionEntries = new HashSet<Map.Entry<HostInfo, Set<SessionToken>>>(sessions.entrySet());
-				}
-				for (Map.Entry<HostInfo, Set<SessionToken>> entry : sessionEntries) {
-					SocketServerInstance instance = null;
-					HashSet<SessionToken> entries = null;
-					synchronized (sessions) {
-						entries = new HashSet<SessionToken>(entry.getValue());
-					}
-					try {
-						instance = getServerInstance(entry.getKey());
-						ILogon logon = instance.getService(ILogon.class);
-						if ("7.1.1".compareTo(instance.getServerVersion()) > 0) { //$NON-NLS-1$
-							for (SessionToken session : entries) {
-								try {
-									logon.assertIdentity(session);
-									logon.ping();
-								} catch (InvalidSessionException e) {
-								}
-							}
-						} else {
-							ArrayList<String> sessionStrings = new ArrayList<String>(entry.getValue().size());
-							for (SessionToken session : entries) {
-								sessionStrings.add(session.getSessionID());
-							}
-							logon.ping(sessionStrings);
-						}
-					} catch (Exception e) {
-						log.log(Level.WARNING, "Error performing keep-alive ping", e); //$NON-NLS-1$
-					} finally {
-						if (instance != null) {
-							instance.shutdown();
-						}
-					}
-				}
-			}
-		}, ServerConnection.PING_INTERVAL, ServerConnection.PING_INTERVAL);
-		this.channelFactory = new OioOjbectChannelFactory(info);
-	}
-	
-	@Override
-	public SocketServerInstance getServerInstance(HostInfo info) throws CommunicationException, IOException {
-		CachedInstance key = null;
-		boolean useCache = this.maxCachedInstances > 0; 
-		if (useCache) {
-			CachedInstance instance = null;
-			key = new CachedInstance(info);
-			synchronized (instancePool) {
-				instance = instancePool.remove(key);
-			}
-			if (instance != null) {
-				ILogon logon = instance.actual.getService(ILogon.class);
-				boolean valid = false;
-				try {
-					Future<?> success = logon.ping();
-					success.get(this.channelFactory.getSoTimeout(), TimeUnit.MILLISECONDS);
-					valid = true;
-				} catch (Exception e) {
-					log.log(Level.FINE, "Error performing ping, will select another instance", e); //$NON-NLS-1$
-				}
-				if (valid) {
-					return instance.proxy;
-				}
-				instance.actual.shutdown();
-				//technically we only want to remove instances with the same inetaddress 
-				while (true) {
-					CachedInstance invalid = null;
-					synchronized (instancePool) {
-						invalid = instancePool.remove(key);
-					}
-					if (invalid == null) {
-						break;
-					}
-					invalid.actual.shutdown();
-				}
-			}
-		}
-		SocketServerInstanceImpl ssii = new SocketServerInstanceImpl(info, getSynchronousTtl());
-		ssii.connect(this.channelFactory);
-		if (useCache) {
-			key.actual = ssii;
-			key.instance = instanceCount.getAndIncrement();
-			//create a proxied socketserverinstance that will pool itself on shutdown
-			key.proxy = (SocketServerInstance)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {SocketServerInstance.class}, new ShutdownHandler(key));
-			return key.proxy;
-		}
-		return ssii;
-	}
-	
-	/**
-	 * @param connectionProperties will be updated with additional information before logon
-	 */
-	public SocketServerConnection getConnection(Properties connectionProperties) throws CommunicationException, ConnectionException {
-		
-		updateConnectionProperties(connectionProperties);
-		
-		TeiidURL url = new TeiidURL(connectionProperties.getProperty(TeiidURL.CONNECTION.SERVER_URL));
-		
-		String discoveryStrategyName = connectionProperties.getProperty(TeiidURL.CONNECTION.DISCOVERY_STRATEGY, URL);
-
-		ServerDiscovery discovery;
-
-		if (URL.equalsIgnoreCase(discoveryStrategyName)) {
-			discovery = new UrlServerDiscovery();
-		} else {
-			try {
-				discovery = (ServerDiscovery)ReflectionHelper.create(discoveryStrategyName, null, this.getClass().getClassLoader());
-			} catch (TeiidException e) {
-				throw new ConnectionException(e);
-			}
-		}
-		
-		discovery.init(url, connectionProperties);
-		
-		return new SocketServerConnection(this, url.isUsingSSL(), discovery, connectionProperties);
-	}
-
-	static void updateConnectionProperties(Properties connectionProperties) {
-		try {
-			InetAddress addr = InetAddress.getLocalHost();
-			connectionProperties.put(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS, addr.getHostAddress());
-			connectionProperties.put(TeiidURL.CONNECTION.CLIENT_HOSTNAME, addr.getCanonicalHostName());
-        } catch (UnknownHostException err1) {
-        	connectionProperties.put(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS, "UnknownClientAddress"); //$NON-NLS-1$
-        }
-	}
-
-	public long getSynchronousTtl() {
-		return synchronousTtl;
-	}
-
-	public void setSynchronousTtl(long synchronousTTL) {
-		this.synchronousTtl = synchronousTTL;
-	}
-
-	public int getMaxCachedInstances() {
-		return maxCachedInstances;
-	}
-	
-	public void setMaxCachedInstances(int maxCachedInstances) {
-		this.maxCachedInstances = maxCachedInstances;
-	}
-	
-	@Override
-	public void connected(SocketServerInstance instance, SessionToken session) {
-		synchronized (sessions) {
-			Set<SessionToken> instanceSessions = sessions.get(instance.getHostInfo());
-			if (instanceSessions == null) {
-				instanceSessions = new HashSet<SessionToken>();
-				sessions.put(instance.getHostInfo(), instanceSessions);
-			}
-			instanceSessions.add(session);
-		}
-	}
-	
-	@Override
-	public void disconnected(SocketServerInstance instance, SessionToken session) {
-		synchronized (sessions) {
-			Set<SessionToken> instanceSessions = sessions.get(instance.getHostInfo());
-			if (instanceSessions != null) {
-				instanceSessions.remove(session);
-				if (instanceSessions.isEmpty()) {
-					sessions.remove(instance.getHostInfo());
-				}
-			}
-		}
-	}
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java (from rev 2802, trunk/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,366 @@
+/*
+ * 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.net.socket;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.teiid.client.security.ILogon;
+import org.teiid.client.security.InvalidSessionException;
+import org.teiid.client.security.SessionToken;
+import org.teiid.core.TeiidException;
+import org.teiid.core.util.PropertiesUtils;
+import org.teiid.core.util.ReflectionHelper;
+import org.teiid.net.CommunicationException;
+import org.teiid.net.ConnectionException;
+import org.teiid.net.HostInfo;
+import org.teiid.net.ServerConnection;
+import org.teiid.net.ServerConnectionFactory;
+import org.teiid.net.TeiidURL;
+
+
+/**
+ * Responsible for creating socket based connections
+ * 
+ * The comm approach is object based and layered.  Connections manage failover and identity.  
+ * ServerInstances represent the service layer to a particular cluster member.  ObjectChannels
+ * abstract the underlying IO.
+ * 
+ */
+public class SocketServerConnectionFactory implements ServerConnectionFactory, SocketServerInstanceFactory {
+
+	private static final String URL = "URL"; //$NON-NLS-1$
+	
+	private static SocketServerConnectionFactory INSTANCE;
+	private static Logger log = Logger.getLogger("org.teiid.client.sockets"); //$NON-NLS-1$
+
+	private final class ShutdownHandler implements InvocationHandler {
+		private final CachedInstance key;
+
+		private ShutdownHandler(CachedInstance key) {
+			this.key = key;
+		}
+
+		@Override
+		public Object invoke(Object arg0, Method arg1, Object[] arg2)
+				throws Throwable {
+			if (arg1.getName().equals("shutdown")) { //$NON-NLS-1$
+				CachedInstance purge = null;
+				if (!key.actual.isOpen()) {
+					return null; //nothing to do
+				}
+				synchronized (instancePool) {
+					instancePool.put(key, key);
+					if (instancePool.size() > maxCachedInstances) {
+						Iterator<CachedInstance> iter = instancePool.keySet().iterator();
+						purge = iter.next();
+						iter.remove();
+					}
+				}
+				if (purge != null) {
+					purge.actual.shutdown();
+				}
+				return null;
+			}
+			try {
+				return arg1.invoke(key.actual, arg2);
+			} catch (InvocationTargetException e) {
+				throw e.getTargetException();
+			}
+		}
+	}
+
+	private static class CachedInstance {
+		HostInfo info;
+		Integer instance;
+		SocketServerInstance actual;
+		SocketServerInstance proxy;
+		
+		public CachedInstance(HostInfo info) {
+			this.info = info;
+		}
+
+		@Override
+		public int hashCode() {
+			return info.hashCode();
+		}
+		
+		@Override
+		public boolean equals(Object obj) {
+			if (this == obj) {
+				return true;
+			}
+			if (!(obj instanceof CachedInstance)) {
+				return false;
+			}
+			CachedInstance other = (CachedInstance) obj;
+			if (!info.equals(other.info)) {
+				return false;
+			}
+			if (instance == null || other.instance == null) {
+				return true;
+			} 
+			return instance.equals(other.instance);
+		}
+	}
+	
+    private ObjectChannelFactory channelFactory;
+	private Timer pingTimer;
+	
+	private HashMap<HostInfo, Set<SessionToken>> sessions = new HashMap<HostInfo, Set<SessionToken>>();
+	
+	//instance pooling
+	private AtomicInteger instanceCount = new AtomicInteger();
+	private Map<CachedInstance, CachedInstance> instancePool = new LinkedHashMap<CachedInstance, CachedInstance>();
+
+	//config properties
+	private long synchronousTtl = 120000l;
+	private int maxCachedInstances=16;
+
+	public static synchronized SocketServerConnectionFactory getInstance() {
+		if (INSTANCE == null) {
+			INSTANCE = new SocketServerConnectionFactory();
+			Properties props = System.getProperties();
+			InputStream is = SocketServerConnectionFactory.class.getResourceAsStream("/teiid-client-settings.properties"); //$NON-NLS-1$
+			if (is != null) {
+				props = new Properties(props);
+				try {
+					props.load(is);
+				} catch (IOException e) {
+					
+				} finally {
+					try {
+						is.close();
+					} catch (IOException e) {
+					}
+				}
+			}
+			INSTANCE.initialize(props);
+		}
+		return INSTANCE;
+	}
+	
+	public SocketServerConnectionFactory() {
+		
+	}
+	
+	public void initialize(Properties info) {
+		PropertiesUtils.setBeanProperties(this, info, "org.teiid.sockets"); //$NON-NLS-1$
+		this.pingTimer = new Timer("SocketPing", true); //$NON-NLS-1$
+		this.pingTimer.schedule(new TimerTask() {
+			
+			@Override
+			public void run() {
+				Set<Map.Entry<HostInfo, Set<SessionToken>>> sessionEntries = null;
+				synchronized (sessions) {
+					sessionEntries = new HashSet<Map.Entry<HostInfo, Set<SessionToken>>>(sessions.entrySet());
+				}
+				for (Map.Entry<HostInfo, Set<SessionToken>> entry : sessionEntries) {
+					SocketServerInstance instance = null;
+					HashSet<SessionToken> entries = null;
+					synchronized (sessions) {
+						entries = new HashSet<SessionToken>(entry.getValue());
+					}
+					try {
+						instance = getServerInstance(entry.getKey());
+						ILogon logon = instance.getService(ILogon.class);
+						if ("7.1.1".compareTo(instance.getServerVersion()) > 0) { //$NON-NLS-1$
+							for (SessionToken session : entries) {
+								try {
+									logon.assertIdentity(session);
+									logon.ping();
+									log.log(Level.FINER, "issueing ping for session:", session); //$NON-NLS-1$
+								} catch (InvalidSessionException e) {
+								}
+							}
+						} else {
+							ArrayList<String> sessionStrings = new ArrayList<String>(entry.getValue().size());
+							for (SessionToken session : entries) {
+								sessionStrings.add(session.getSessionID());
+							}
+							logon.ping(sessionStrings);
+							log.log(Level.FINER, "issueing ping for sessions:", sessionStrings); //$NON-NLS-1$
+						}
+					} catch (Exception e) {
+						log.log(Level.WARNING, "Error performing keep-alive ping", e); //$NON-NLS-1$
+					} finally {
+						if (instance != null) {
+							instance.shutdown();
+						}
+					}
+				}
+			}
+		}, ServerConnection.PING_INTERVAL, ServerConnection.PING_INTERVAL);
+		this.channelFactory = new OioOjbectChannelFactory(info);
+	}
+	
+	@Override
+	public SocketServerInstance getServerInstance(HostInfo info) throws CommunicationException, IOException {
+		CachedInstance key = null;
+		boolean useCache = this.maxCachedInstances > 0; 
+		if (useCache) {
+			CachedInstance instance = null;
+			key = new CachedInstance(info);
+			synchronized (instancePool) {
+				instance = instancePool.remove(key);
+			}
+			if (instance != null) {
+				ILogon logon = instance.actual.getService(ILogon.class);
+				boolean valid = false;
+				try {
+					Future<?> success = logon.ping();
+					success.get(this.channelFactory.getSoTimeout(), TimeUnit.MILLISECONDS);
+					valid = true;
+				} catch (Exception e) {
+					log.log(Level.FINE, "Error performing ping, will select another instance", e); //$NON-NLS-1$
+				}
+				if (valid) {
+					return instance.proxy;
+				}
+				instance.actual.shutdown();
+				//technically we only want to remove instances with the same inetaddress 
+				while (true) {
+					CachedInstance invalid = null;
+					synchronized (instancePool) {
+						invalid = instancePool.remove(key);
+					}
+					if (invalid == null) {
+						break;
+					}
+					invalid.actual.shutdown();
+				}
+			}
+		}
+		SocketServerInstanceImpl ssii = new SocketServerInstanceImpl(info, getSynchronousTtl());
+		ssii.connect(this.channelFactory);
+		if (useCache) {
+			key.actual = ssii;
+			key.instance = instanceCount.getAndIncrement();
+			//create a proxied socketserverinstance that will pool itself on shutdown
+			key.proxy = (SocketServerInstance)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {SocketServerInstance.class}, new ShutdownHandler(key));
+			return key.proxy;
+		}
+		return ssii;
+	}
+	
+	/**
+	 * @param connectionProperties will be updated with additional information before logon
+	 */
+	public SocketServerConnection getConnection(Properties connectionProperties) throws CommunicationException, ConnectionException {
+		
+		updateConnectionProperties(connectionProperties);
+		
+		TeiidURL url = new TeiidURL(connectionProperties.getProperty(TeiidURL.CONNECTION.SERVER_URL));
+		
+		String discoveryStrategyName = connectionProperties.getProperty(TeiidURL.CONNECTION.DISCOVERY_STRATEGY, URL);
+
+		ServerDiscovery discovery;
+
+		if (URL.equalsIgnoreCase(discoveryStrategyName)) {
+			discovery = new UrlServerDiscovery();
+		} else {
+			try {
+				discovery = (ServerDiscovery)ReflectionHelper.create(discoveryStrategyName, null, this.getClass().getClassLoader());
+			} catch (TeiidException e) {
+				throw new ConnectionException(e);
+			}
+		}
+		
+		discovery.init(url, connectionProperties);
+		
+		return new SocketServerConnection(this, url.isUsingSSL(), discovery, connectionProperties);
+	}
+
+	static void updateConnectionProperties(Properties connectionProperties) {
+		try {
+			InetAddress addr = InetAddress.getLocalHost();
+			connectionProperties.put(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS, addr.getHostAddress());
+			connectionProperties.put(TeiidURL.CONNECTION.CLIENT_HOSTNAME, addr.getCanonicalHostName());
+        } catch (UnknownHostException err1) {
+        	connectionProperties.put(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS, "UnknownClientAddress"); //$NON-NLS-1$
+        }
+	}
+
+	public long getSynchronousTtl() {
+		return synchronousTtl;
+	}
+
+	public void setSynchronousTtl(long synchronousTTL) {
+		this.synchronousTtl = synchronousTTL;
+	}
+
+	public int getMaxCachedInstances() {
+		return maxCachedInstances;
+	}
+	
+	public void setMaxCachedInstances(int maxCachedInstances) {
+		this.maxCachedInstances = maxCachedInstances;
+	}
+	
+	@Override
+	public void connected(SocketServerInstance instance, SessionToken session) {
+		synchronized (sessions) {
+			Set<SessionToken> instanceSessions = sessions.get(instance.getHostInfo());
+			if (instanceSessions == null) {
+				instanceSessions = new HashSet<SessionToken>();
+				sessions.put(instance.getHostInfo(), instanceSessions);
+			}
+			instanceSessions.add(session);
+		}
+	}
+	
+	@Override
+	public void disconnected(SocketServerInstance instance, SessionToken session) {
+		synchronized (sessions) {
+			Set<SessionToken> instanceSessions = sessions.get(instance.getHostInfo());
+			if (instanceSessions != null) {
+				instanceSessions.remove(session);
+				if (instanceSessions.isEmpty()) {
+					sessions.remove(instance.getHostInfo());
+				}
+			}
+		}
+	}
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/netty/handler/codec/serialization/CompactObjectOutputStream.java
===================================================================
--- trunk/client/src/main/java/org/teiid/netty/handler/codec/serialization/CompactObjectOutputStream.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/netty/handler/codec/serialization/CompactObjectOutputStream.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,292 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- *
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @author tags. See the COPYRIGHT.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This 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 software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.teiid.netty.handler.codec.serialization;
-
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.Serializable;
-import java.nio.charset.Charset;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.SQLException;
-import java.sql.SQLXML;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-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.metadata.ParameterInfo;
-import org.teiid.client.plan.Annotation;
-import org.teiid.client.plan.PlanNode;
-import org.teiid.client.security.ILogon;
-import org.teiid.client.security.InvalidSessionException;
-import org.teiid.client.security.LogonException;
-import org.teiid.client.security.LogonResult;
-import org.teiid.client.security.TeiidSecurityException;
-import org.teiid.client.security.SessionToken;
-import org.teiid.client.util.ExceptionHolder;
-import org.teiid.client.xa.XATransactionException;
-import org.teiid.client.xa.XidImpl;
-import org.teiid.core.ComponentNotFoundException;
-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.BlobImpl;
-import org.teiid.core.types.BlobType;
-import org.teiid.core.types.ClobImpl;
-import org.teiid.core.types.ClobType;
-import org.teiid.core.types.InputStreamFactory;
-import org.teiid.core.types.SQLXMLImpl;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.types.XMLType;
-import org.teiid.core.types.InputStreamFactory.StreamFactoryReference;
-import org.teiid.core.util.ReaderInputStream;
-import org.teiid.net.socket.Handshake;
-import org.teiid.net.socket.Message;
-import org.teiid.net.socket.ServiceInvocationStruct;
-
-
-/**
- * @author The Netty Project (netty-dev at lists.jboss.org)
- * @author Trustin Lee (tlee at redhat.com)
- *
- * @version $Rev: 6 $, $Date: 2008-08-07 20:40:10 -0500 (Thu, 07 Aug 2008) $
- *
- */
-public class CompactObjectOutputStream extends ObjectOutputStream {
-
-    static final int TYPE_PRIMITIVE = 0;
-    static final int TYPE_NON_PRIMITIVE = 1;
-    
-    public static final Map<Class<?>, Integer> KNOWN_CLASSES = new HashMap<Class<?>, Integer>();
-    public static final Map<Integer, Class<?>> KNOWN_CODES = new HashMap<Integer, Class<?>>();
-    
-    private List<InputStream> streams = new LinkedList<InputStream>();
-    private List<StreamFactoryReference> references = new LinkedList<StreamFactoryReference>();
-    
-    public static void addKnownClass(Class<?> clazz, byte code) {
-    	KNOWN_CLASSES.put(clazz, Integer.valueOf(code));
-    	if (KNOWN_CODES.put(Integer.valueOf(code), clazz) != null) {
-    		throw new TeiidRuntimeException("Duplicate class"); //$NON-NLS-1$
-    	}
-    }
-    
-    static {
-    	addKnownClass(ServiceInvocationStruct.class, (byte)2);
-    	addKnownClass(Handshake.class, (byte)3);
-    	addKnownClass(Message.class, (byte)4);
-    	addKnownClass(SerializableReader.class, (byte)5);
-    	addKnownClass(SerializableInputStream.class, (byte)6);
-    	
-    	addKnownClass(DQP.class, (byte)10);
-    	addKnownClass(LobChunk.class, (byte)11);
-    	addKnownClass(RequestMessage.class, (byte)12);
-    	addKnownClass(ResultsMessage.class, (byte)13);
-    	addKnownClass(PlanNode.class, (byte)14);
-    	addKnownClass(PlanNode.Property.class, (byte)15);
-    	addKnownClass(Annotation.class, (byte)16);
-    	addKnownClass(MetadataResult.class, (byte)17);
-    	addKnownClass(ParameterInfo.class, (byte)18);
-    	addKnownClass(XidImpl.class, (byte)19);
-    	addKnownClass(BlobImpl.class, (byte)20);
-    	addKnownClass(ClobImpl.class, (byte)21);
-    	addKnownClass(SQLXMLImpl.class, (byte)22);
-    	addKnownClass(BlobType.class, (byte)23);
-    	addKnownClass(ClobType.class, (byte)24);
-    	addKnownClass(XMLType.class, (byte)25);
-    	addKnownClass(XATransactionException.class, (byte)26);
-    	
-    	addKnownClass(ILogon.class, (byte)30);
-    	addKnownClass(LogonResult.class, (byte)31);
-    	addKnownClass(SessionToken.class, (byte)32);
-    	addKnownClass(LogonException.class, (byte)33);
-    	addKnownClass(TeiidSecurityException.class, (byte)34);
-    	addKnownClass(InvalidSessionException.class, (byte)35);
-    	
-    	addKnownClass(ExceptionHolder.class, (byte)40);
-    	addKnownClass(TeiidRuntimeException.class, (byte)41);
-    	addKnownClass(TeiidComponentException.class, (byte)42);
-    	addKnownClass(TeiidException.class, (byte)43);
-    	addKnownClass(TeiidProcessingException.class, (byte)44);
-    	addKnownClass(ComponentNotFoundException.class, (byte)45);
-    }
-    
-    public CompactObjectOutputStream(OutputStream out) throws IOException {
-        super(out);
-        enableReplaceObject(true);
-    }
-    
-    public List<InputStream> getStreams() {
-		return streams;
-	}
-    
-    public List<StreamFactoryReference> getReferences() {
-		return references;
-	}
-
-    @Override
-    protected void writeStreamHeader() throws IOException {
-        writeByte(STREAM_VERSION);
-    }
-
-    @Override
-    protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException {
-        if (desc.forClass().isPrimitive() 
-        		|| !(Externalizable.class.isAssignableFrom(desc.forClass()))) {
-            write(TYPE_PRIMITIVE);
-            super.writeClassDescriptor(desc);
-        } else {
-        	Integer b = KNOWN_CLASSES.get(desc.forClass());
-        	if (b != null) {
-        		write(b.intValue());
-        	} else {
-	            write(TYPE_NON_PRIMITIVE);
-	            writeUTF(desc.getName());
-        	}
-        }
-    }
-        
-    @Override
-    protected Object replaceObject(Object obj) throws IOException {
-    	if (obj instanceof Serializable) {
-    		return obj;
-    	}
-		try {
-	    	if (obj instanceof Reader) {
-	    		streams.add(new ReaderInputStream((Reader)obj, Charset.forName(Streamable.ENCODING)));
-	    		StreamFactoryReference sfr = new SerializableReader();
-	    		references.add(sfr);
-	    		return sfr;
-	    	} else if (obj instanceof InputStream) {
-	    		streams.add((InputStream)obj);
-	    		StreamFactoryReference sfr = new SerializableInputStream();
-	    		references.add(sfr);
-	    		return sfr;
-	    	} else if (obj instanceof SQLXML) {
-				streams.add(((SQLXML)obj).getBinaryStream());
-	    		StreamFactoryReference sfr = new SQLXMLImpl();
-	    		references.add(sfr);
-	    		return sfr;
-	    	} else if (obj instanceof Clob) {
-	    		//TODO: see if this is a ClobImpl and grab the underlying stream
-	    		streams.add(new ReaderInputStream(((Clob)obj).getCharacterStream(), Charset.forName(Streamable.ENCODING)));
-	    		StreamFactoryReference sfr = new ClobImpl();
-	    		references.add(sfr);
-	    		return sfr;
-	    	} else if (obj instanceof Blob) {
-	    		streams.add(((Blob)obj).getBinaryStream());
-	    		StreamFactoryReference sfr = new BlobImpl();
-	    		references.add(sfr);
-	    		return sfr;
-	    	}
-		} catch (SQLException e) {
-			throw new IOException(e);
-		}
-    	return super.replaceObject(obj);
-    }
-    
-    static class SerializableInputStream extends InputStream implements Externalizable, StreamFactoryReference {
-
-		private InputStreamFactory isf;
-    	private InputStream is;
-    	
-    	public SerializableInputStream() {
-		}
-    	
-    	public void setStreamFactory(InputStreamFactory streamFactory) {
-    		this.isf = streamFactory;
-    	}
-    	
-		@Override
-		public int read() throws IOException {
-			if (is == null) {
-				is = isf.getInputStream();
-			}
-			return is.read();
-		}
-		
-		@Override
-		public void close() throws IOException {
-			isf.free();
-		}
-
-		@Override
-		public void readExternal(ObjectInput in) throws IOException,
-				ClassNotFoundException {
-		}
-
-		@Override
-		public void writeExternal(ObjectOutput out) throws IOException {
-		}
-    }
-    
-    static class SerializableReader extends Reader implements Externalizable, StreamFactoryReference {
-
-		private InputStreamFactory isf;
-    	private Reader r;
-    	
-    	public SerializableReader() {
-		}
-    	
-    	public void setStreamFactory(InputStreamFactory streamFactory) {
-    		this.isf = streamFactory;
-    	}
-
-		@Override
-		public void close() throws IOException {
-			isf.free();
-		}
-
-		@Override
-		public int read(char[] cbuf, int off, int len) throws IOException {
-			if (r == null) {
-				r = new InputStreamReader(isf.getInputStream(), Streamable.ENCODING);
-			}
-			return r.read(cbuf, off, len);
-		}
-
-		@Override
-		public void readExternal(ObjectInput in) throws IOException,
-				ClassNotFoundException {
-		}
-
-		@Override
-		public void writeExternal(ObjectOutput out) throws IOException {
-		}
-    }
-    
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/netty/handler/codec/serialization/CompactObjectOutputStream.java (from rev 2802, trunk/client/src/main/java/org/teiid/netty/handler/codec/serialization/CompactObjectOutputStream.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/netty/handler/codec/serialization/CompactObjectOutputStream.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/main/java/org/teiid/netty/handler/codec/serialization/CompactObjectOutputStream.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,316 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @author tags. See the COPYRIGHT.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This 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 software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.teiid.netty.handler.codec.serialization;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.Serializable;
+import java.nio.charset.Charset;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+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.metadata.ParameterInfo;
+import org.teiid.client.plan.Annotation;
+import org.teiid.client.plan.PlanNode;
+import org.teiid.client.security.ILogon;
+import org.teiid.client.security.InvalidSessionException;
+import org.teiid.client.security.LogonException;
+import org.teiid.client.security.LogonResult;
+import org.teiid.client.security.TeiidSecurityException;
+import org.teiid.client.security.SessionToken;
+import org.teiid.client.util.ExceptionHolder;
+import org.teiid.client.xa.XATransactionException;
+import org.teiid.client.xa.XidImpl;
+import org.teiid.core.ComponentNotFoundException;
+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.BaseLob;
+import org.teiid.core.types.BlobImpl;
+import org.teiid.core.types.BlobType;
+import org.teiid.core.types.ClobImpl;
+import org.teiid.core.types.ClobType;
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.SQLXMLImpl;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.types.XMLType;
+import org.teiid.core.types.InputStreamFactory.StreamFactoryReference;
+import org.teiid.core.util.ReaderInputStream;
+import org.teiid.net.socket.Handshake;
+import org.teiid.net.socket.Message;
+import org.teiid.net.socket.ServiceInvocationStruct;
+
+
+/**
+ * @author The Netty Project (netty-dev at lists.jboss.org)
+ * @author Trustin Lee (tlee at redhat.com)
+ *
+ * @version $Rev: 6 $, $Date: 2008-08-07 20:40:10 -0500 (Thu, 07 Aug 2008) $
+ *
+ */
+public class CompactObjectOutputStream extends ObjectOutputStream {
+
+    static final int TYPE_PRIMITIVE = 0;
+    static final int TYPE_NON_PRIMITIVE = 1;
+    
+    public static final Map<Class<?>, Integer> KNOWN_CLASSES = new HashMap<Class<?>, Integer>();
+    public static final Map<Integer, Class<?>> KNOWN_CODES = new HashMap<Integer, Class<?>>();
+    
+    private List<InputStream> streams = new LinkedList<InputStream>();
+    private List<StreamFactoryReference> references = new LinkedList<StreamFactoryReference>();
+    
+    public static void addKnownClass(Class<?> clazz, byte code) {
+    	KNOWN_CLASSES.put(clazz, Integer.valueOf(code));
+    	if (KNOWN_CODES.put(Integer.valueOf(code), clazz) != null) {
+    		throw new TeiidRuntimeException("Duplicate class"); //$NON-NLS-1$
+    	}
+    }
+    
+    static {
+    	addKnownClass(ServiceInvocationStruct.class, (byte)2);
+    	addKnownClass(Handshake.class, (byte)3);
+    	addKnownClass(Message.class, (byte)4);
+    	addKnownClass(SerializableReader.class, (byte)5);
+    	addKnownClass(SerializableInputStream.class, (byte)6);
+    	
+    	addKnownClass(DQP.class, (byte)10);
+    	addKnownClass(LobChunk.class, (byte)11);
+    	addKnownClass(RequestMessage.class, (byte)12);
+    	addKnownClass(ResultsMessage.class, (byte)13);
+    	addKnownClass(PlanNode.class, (byte)14);
+    	addKnownClass(PlanNode.Property.class, (byte)15);
+    	addKnownClass(Annotation.class, (byte)16);
+    	addKnownClass(MetadataResult.class, (byte)17);
+    	addKnownClass(ParameterInfo.class, (byte)18);
+    	addKnownClass(XidImpl.class, (byte)19);
+    	addKnownClass(BlobImpl.class, (byte)20);
+    	addKnownClass(ClobImpl.class, (byte)21);
+    	addKnownClass(SQLXMLImpl.class, (byte)22);
+    	addKnownClass(BlobType.class, (byte)23);
+    	addKnownClass(ClobType.class, (byte)24);
+    	addKnownClass(XMLType.class, (byte)25);
+    	addKnownClass(XATransactionException.class, (byte)26);
+    	
+    	addKnownClass(ILogon.class, (byte)30);
+    	addKnownClass(LogonResult.class, (byte)31);
+    	addKnownClass(SessionToken.class, (byte)32);
+    	addKnownClass(LogonException.class, (byte)33);
+    	addKnownClass(TeiidSecurityException.class, (byte)34);
+    	addKnownClass(InvalidSessionException.class, (byte)35);
+    	
+    	addKnownClass(ExceptionHolder.class, (byte)40);
+    	addKnownClass(TeiidRuntimeException.class, (byte)41);
+    	addKnownClass(TeiidComponentException.class, (byte)42);
+    	addKnownClass(TeiidException.class, (byte)43);
+    	addKnownClass(TeiidProcessingException.class, (byte)44);
+    	addKnownClass(ComponentNotFoundException.class, (byte)45);
+    }
+    
+    public CompactObjectOutputStream(OutputStream out) throws IOException {
+        super(out);
+        enableReplaceObject(true);
+    }
+    
+    public List<InputStream> getStreams() {
+		return streams;
+	}
+    
+    public List<StreamFactoryReference> getReferences() {
+		return references;
+	}
+
+    @Override
+    protected void writeStreamHeader() throws IOException {
+        writeByte(STREAM_VERSION);
+    }
+
+    @Override
+    protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException {
+        if (desc.forClass().isPrimitive() 
+        		|| !(Externalizable.class.isAssignableFrom(desc.forClass()))) {
+            write(TYPE_PRIMITIVE);
+            super.writeClassDescriptor(desc);
+        } else {
+        	Integer b = KNOWN_CLASSES.get(desc.forClass());
+        	if (b != null) {
+        		write(b.intValue());
+        	} else {
+	            write(TYPE_NON_PRIMITIVE);
+	            writeUTF(desc.getName());
+        	}
+        }
+    }
+        
+    @Override
+    protected Object replaceObject(Object obj) throws IOException {
+    	if (obj instanceof BaseLob) {
+    		try {
+		    	if (obj instanceof SQLXMLImpl) {
+					streams.add(((SQLXMLImpl)obj).getBinaryStream());
+		    		StreamFactoryReference sfr = new SQLXMLImpl();
+		    		references.add(sfr);
+		    		return sfr;
+		    	} else if (obj instanceof ClobImpl) {
+		    		streams.add(new ReaderInputStream(((ClobImpl)obj).getCharacterStream(), Charset.forName(Streamable.ENCODING)));
+		    		StreamFactoryReference sfr = new ClobImpl();
+		    		references.add(sfr);
+		    		return sfr;
+		    	} else if (obj instanceof BlobImpl) {
+		    		streams.add(((Blob)obj).getBinaryStream());
+		    		StreamFactoryReference sfr = new BlobImpl();
+		    		references.add(sfr);
+		    		return sfr;
+		    	}
+    		} catch (SQLException e) {
+    			throw new IOException(e);
+    		}
+    	}
+    	else if (obj instanceof Serializable) {
+    		return obj;
+    	}
+    	else {
+			try {
+		    	if (obj instanceof Reader) {
+		    		streams.add(new ReaderInputStream((Reader)obj, Charset.forName(Streamable.ENCODING)));
+		    		StreamFactoryReference sfr = new SerializableReader();
+		    		references.add(sfr);
+		    		return sfr;
+		    	} else if (obj instanceof InputStream) {
+		    		streams.add((InputStream)obj);
+		    		StreamFactoryReference sfr = new SerializableInputStream();
+		    		references.add(sfr);
+		    		return sfr;
+		    	} else if (obj instanceof SQLXML) {
+					streams.add(((SQLXML)obj).getBinaryStream());
+		    		StreamFactoryReference sfr = new SQLXMLImpl();
+		    		references.add(sfr);
+		    		return sfr;
+		    	} else if (obj instanceof Clob) {
+		    		streams.add(new ReaderInputStream(((Clob)obj).getCharacterStream(), Charset.forName(Streamable.ENCODING)));
+		    		StreamFactoryReference sfr = new ClobImpl();
+		    		references.add(sfr);
+		    		return sfr;
+		    	} else if (obj instanceof Blob) {
+		    		streams.add(((Blob)obj).getBinaryStream());
+		    		StreamFactoryReference sfr = new BlobImpl();
+		    		references.add(sfr);
+		    		return sfr;
+		    	}
+			} catch (SQLException e) {
+				throw new IOException(e);
+			}
+    	}
+    	return super.replaceObject(obj);
+    }
+    
+    static class SerializableInputStream extends InputStream implements Externalizable, StreamFactoryReference {
+
+		private InputStreamFactory isf;
+    	private InputStream is;
+    	
+    	public SerializableInputStream() {
+		}
+    	
+    	public void setStreamFactory(InputStreamFactory streamFactory) {
+    		this.isf = streamFactory;
+    	}
+    	
+		@Override
+		public int read() throws IOException {
+			if (is == null) {
+				is = isf.getInputStream();
+			}
+			return is.read();
+		}
+		
+		@Override
+		public void close() throws IOException {
+			isf.free();
+		}
+
+		@Override
+		public void readExternal(ObjectInput in) throws IOException,
+				ClassNotFoundException {
+		}
+
+		@Override
+		public void writeExternal(ObjectOutput out) throws IOException {
+		}
+    }
+    
+    static class SerializableReader extends Reader implements Externalizable, StreamFactoryReference {
+
+		private InputStreamFactory isf;
+    	private Reader r;
+    	
+    	public SerializableReader() {
+		}
+    	
+    	public void setStreamFactory(InputStreamFactory streamFactory) {
+    		this.isf = streamFactory;
+    	}
+
+		@Override
+		public void close() throws IOException {
+			isf.free();
+		}
+
+		@Override
+		public int read(char[] cbuf, int off, int len) throws IOException {
+			if (r == null) {
+				r = new InputStreamReader(isf.getInputStream(), Streamable.ENCODING);
+			}
+			return r.read(cbuf, off, len);
+		}
+
+		@Override
+		public void readExternal(ObjectInput in) throws IOException,
+				ClassNotFoundException {
+		}
+
+		@Override
+		public void writeExternal(ObjectOutput out) throws IOException {
+		}
+    }
+    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/jdbc/TestPreparedStatement.java
===================================================================
--- trunk/client/src/test/java/org/teiid/jdbc/TestPreparedStatement.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/jdbc/TestPreparedStatement.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,343 +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.jdbc;
-
-import static org.junit.Assert.*;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.TimeZone;
-
-import org.junit.Test;
-import org.mockito.Matchers;
-import org.mockito.Mockito;
-import org.teiid.client.DQP;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.client.RequestMessage.ResultsMode;
-import org.teiid.client.security.LogonResult;
-import org.teiid.client.util.ResultsFuture;
-import org.teiid.jdbc.ConnectionImpl;
-import org.teiid.jdbc.PreparedStatementImpl;
-import org.teiid.jdbc.TeiidSQLException;
-import org.teiid.net.ServerConnection;
-
-
-/**
- * Test case to validate general operations on an <code>MMPreparedStatement
- * </code> 
- */
-public class TestPreparedStatement {
-
-	/**
-	 * Test that <code>MMPreparedStatement</code>'s <code>execute()</code> method
-	 * will throw a <code>MMSQLException</code> if a connection does not exist.
-	 * 
-	 * @throws Exception
-	 */
-	@Test(expected=TeiidSQLException.class) public void testUpdateException() throws Exception {
-		PreparedStatementImpl statement = getMMPreparedStatement("delete from table"); //$NON-NLS-1$
-		statement.execute();
-	}
-	
-	/**
-	 * Verify that the <code>executeBatch()</code> method of <code>
-	 * MMPreparedStatement</code> is resulting in the correct command, 
-	 * parameter values for each command of the batch, and the request type 
-	 * are being set in the request message that would normally be sent to the 
-	 * server.
-	 *   
-	 * @throws Exception
-	 */
-	@Test public void testBatchedUpdateExecution() throws Exception {
-		// Build up a fake connection instance for use with the prepared statement
-		ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
-		DQP dqp = Mockito.mock(DQP.class);
-		ServerConnection serverConn = Mockito.mock(ServerConnection.class);
-		LogonResult logonResult = Mockito.mock(LogonResult.class);
-		
-		// stub methods
-		Mockito.stub(conn.getServerConnection()).toReturn(serverConn);
-		Mockito.stub(serverConn.getLogonResult()).toReturn(logonResult);
-		Mockito.stub(logonResult.getTimeZone()).toReturn(TimeZone.getDefault());
-
-		// a dummy result message that is specific to this test case
-		ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>(); 
-		Mockito.stub(dqp.executeRequest(Matchers.anyLong(), (RequestMessage)Matchers.anyObject())).toReturn(results);
-		ResultsMessage rm = new ResultsMessage();
-		rm.setResults(new List<?>[] {Arrays.asList(0), Arrays.asList(0), Arrays.asList(0)});
-		rm.setUpdateResult(true);
-		results.getResultsReceiver().receiveResults(rm);
-		Mockito.stub(conn.getDQP()).toReturn(dqp);
-		
-		// some update SQL
-		String sqlCommand = "delete from table where col=?"; //$NON-NLS-1$
-		TestableMMPreparedStatement statement = (TestableMMPreparedStatement) getMMPreparedStatement(conn, sqlCommand);
-
-		ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(3);
-		// Add some batches and their parameter values
-		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(1) } ) ) );
-		statement.setInt(1, new Integer(1));
-		statement.addBatch();
-		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(2) } ) ) );
-		statement.setInt(1, new Integer(2));
-		statement.addBatch();
-		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(3) } ) ) );
-		statement.setInt(1, new Integer(3));
-		statement.addBatch();
-		
-		// execute the batch and verify that it matches our dummy results 
-		// message set earlier
-		assertTrue(Arrays.equals(new int[] {0, 0, 0}, statement.executeBatch()));
-		
-		// Now verify the statement's RequestMessage is what we expect 
-		assertEquals("Command does not match", sqlCommand, statement.requestMessage.getCommandString()); //$NON-NLS-1$
-		assertEquals("Parameter values do not match", expectedParameterValues, statement.requestMessage.getParameterValues()); //$NON-NLS-1$
-		assertTrue("RequestMessage.isBatchedUpdate should be true", statement.requestMessage.isBatchedUpdate()); //$NON-NLS-1$
-		assertFalse("RequestMessage.isCallableStatement should be false", statement.requestMessage.isCallableStatement()); //$NON-NLS-1$
-		assertTrue("RequestMessage.isPreparedStatement should be true", statement.requestMessage.isPreparedStatement()); //$NON-NLS-1$
-	}
-	
-	/**
-	 * Verify that the <code>clearBatch()</code> method of 
-	 * <code>MMPreparedStatement</code> is clearing the list of batched 
-	 * commands.
-	 * <p>
-	 * This is done by first adding command parameter values to the batch and 
-	 * then invoking the <code>clearBatch()</code> method.
-	 *   
-	 * @throws Exception
-	 */
-	@Test public void testClearBatch() throws Exception {
-		PreparedStatementImpl statement = getMMPreparedStatement("delete from table where col=?"); //$NON-NLS-1$
-		// Add some stuff
-		statement.setInt(1, new Integer(1));
-		statement.addBatch();
-		statement.setInt(1, new Integer(2));
-		statement.addBatch();
-		// Make sure something is really there
-		assertTrue("MMPreparedStatement.ParameterValuesList should not be empty", statement.getParameterValuesList().size() > 0); //$NON-NLS-1$
-		// Now clear it
-		statement.clearBatch();
-		assertTrue("MMPreparedStatement.ParameterValuesList should be empty", statement.getParameterValuesList().size() == 0); //$NON-NLS-1$
-	}
-
-	/**
-	 * Adds additional batches of command parameter values to a prepared 
-	 * statement after a previous list has been cleared.
-	 * <p>
-	 * This is done by first adding command parameter values to the batch and 
-	 * then invoking the <code>clearBatch()</code> method.  Then a different 
-	 * set of command parameter values are added to the existing batch command.
-	 * <p>
-	 * The expected result is the command parameter list for the batches will 
-	 * only reflect what was added after <code>clearBatch()</code> was invoked.  
-	 *   
-	 * @throws Exception
-	 */
-	@Test public void testClearBatchAddBatch() throws Exception {
-		PreparedStatementImpl statement = getMMPreparedStatement("delete from table where col=?"); //$NON-NLS-1$
-		
-		statement.setInt(1, new Integer(1));
-		statement.addBatch();
-		statement.setInt(1, new Integer(2));
-		statement.addBatch();
-		// Make sure something is really there
-		assertTrue("MMPreparedStatement.ParameterValuesList should not be empty", statement.getParameterValuesList().size() > 0); //$NON-NLS-1$
-		// Now clear it
-		statement.clearBatch();
-		// Make sure it is empty now
-		assertTrue("MMPreparedStatement.ParameterValuesList should be empty", statement.getParameterValuesList().size() == 0); //$NON-NLS-1$
-
-		ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(1);
-		
-		// Now add something for validation 
-		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(5) } ) ) );
-		statement.setInt(1, new Integer(5));
-		statement.addBatch();
-		assertEquals("MMPreparedStatement.ParameterValuesList does not match", expectedParameterValues, statement.getParameterValuesList()); //$NON-NLS-1$
-	}
-
-	/**
-	 * Test the <code>addBatch()</code> method of <code>MMPreparedStatement</code> 
-	 * to verify that the command parameter values of the batch are added to the 
-	 * command parameter values list.
-	 *   
-	 * @throws Exception
-	 */
-	@Test public void testAddBatch() throws Exception {
-		PreparedStatementImpl statement = getMMPreparedStatement("delete from table where col=?"); //$NON-NLS-1$
-
-		ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(1);
-		
-		// First we add a single batch 
-		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(1) } ) ) );
-		statement.setInt(1, new Integer(1));
-		statement.addBatch();
-		assertEquals("MMPreparedStatement.ParameterValuesList does not match", expectedParameterValues, statement.getParameterValuesList()); //$NON-NLS-1$
-
-		// Now add some more batches just for sanity sake
-		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(3) } ) ) );
-		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(5) } ) ) );
-		statement.setInt(1, new Integer(3));
-		statement.addBatch();
-		statement.setInt(1, new Integer(5));
-		statement.addBatch();
-		assertEquals("MMPreparedStatement.ParameterValuesList does not match", expectedParameterValues, statement.getParameterValuesList()); //$NON-NLS-1$
-	}
-
-	/**
-	 * Test the <code>addBatch()</code> method of <code>MMPreparedStatement</code> 
-	 * using a batch with an empty parameter value list.  The test will verify 
-	 * no failures occur when there are no command parameter values defined 
-	 * when the <code>addBatch()</code> method is invoked.
-	 * <p>
-	 * It is valid to add an empty parameter value list to a batch list.
-	 * <p>
-	 * For example:
-	 * <p>
-	 * <code>PreparedStatement stmt = conn.prepareStatement(sql);<br \>
-	 *  stmt.addBatch();<br \>
-	 *  stmt.addBatch();<br \>
-	 *  stmt.executeBatch();</code>
-	 *   
-	 * @throws Exception
-	 */
-	@Test public void testAddBatchNoParameterValues() throws Exception {
-		PreparedStatementImpl statement = getMMPreparedStatement("delete from table where col=?"); //$NON-NLS-1$
-		
-		// This will hold our expected values list
-		ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(1);
-		
-		// First batch has an empty parameter value list
-		expectedParameterValues.add( new ArrayList<Object>(Collections.emptyList()) );
-
-		// No values have been set  so we are adding a batch with an empty 
-		// parameter value list
-		statement.addBatch();
-
-		// Second batch contains a parameter value list
-		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(1) } ) ) );
-
-		// We now are adding a batch that does have parameter values
-		statement.setInt(1, new Integer(1));
-		statement.addBatch();
-
-		// Check to see if our statement contains our expected parameter value list
-		assertEquals("MMPreparedStatement.ParameterValuesList does not match", expectedParameterValues, statement.getParameterValuesList()); //$NON-NLS-1$
-	}
-
-	/**
-	 * A helper method to get an <code>MMPreparedStatement</code> that can be 
-	 * used for simple test cases.
-	 * <p>
-	 * The returned value is an instance of <code>TestableMMPreparedStatement</code>
-	 * <p>
-	 * This method invokes <code>getMMPreparedStatement(final MMConnection conn, 
-	 * final String sql)</code> with a fake connection object constructed by 
-	 * <code>Mockito</code>.
-	 *   
-	 * @param sql the query for the prepared statement
-	 * @return an instance of TestableMMPreparedStatement
-	 * @throws SQLException
-	 */
-	protected PreparedStatementImpl getMMPreparedStatement(final String sql) throws SQLException {
-		ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
-		ServerConnection serverConn = Mockito.mock(ServerConnection.class);
-		LogonResult logonResult = Mockito.mock(LogonResult.class);
-		
-		Mockito.stub(conn.getServerConnection()).toReturn(serverConn);
-		Mockito.stub(serverConn.getLogonResult()).toReturn(logonResult);
-		Mockito.stub(logonResult.getTimeZone()).toReturn(TimeZone.getDefault());
-
-		return getMMPreparedStatement(conn, sql);
-	}
-	
-	/**
-	 * A helper method to get an <code>MMPreparedStatement</code> that can be 
-	 * used for simple test cases.
-	 * <p>
-	 * The returned value is an instance of <code>TestableMMPreparedStatement</code>
-	 * <p>
-	 * <code>conn</code> should be a valid instance of <code>MMConnection</code> 
-	 * or this method will fail.
-	 * 
-	 * @param conn an instance of <code>MMConnection</code>
-	 * @param sql the query for the prepared statement
-	 * @return an instance of TestableMMPreparedStatement
-	 * @throws SQLException
-	 */
-	protected PreparedStatementImpl getMMPreparedStatement(final ConnectionImpl conn, final String sql) throws SQLException {
-		TestableMMPreparedStatement statement = new TestableMMPreparedStatement(conn, sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
-		
-		// Make sure everything is empty on start
-		assertTrue("MMPreparedStatement.ParameterValuesList should be empty", statement.getParameterValuesList().size() == 0); //$NON-NLS-1$
-		assertTrue("MMPreparedStatement.ParameterValues should be empty", statement.getParameterValues().size() == 0); //$NON-NLS-1$
-
-		return statement;
-	}
-	
-	/**
-	 * Represents an extension to <code>MMPreparedStatement</code> that 
-	 * gives access to the <code>RequestMessage</code> that is passed 
-	 * around inside <code>MMPreparedStatement</code>. 
-	 * <p>
-	 * This extension simply adds a field named <code>requestMessage</code> 
-	 * which is <code>public</code>.  This field gets set when the <code>protected</code>
-	 * method <code>createRequestMessage()</code> is called.
-	 * <p>
-	 * This extension also overrides <code>RequestMessage createRequestMessage(String[] commands,
-	 *			boolean isBatchedCommand, Boolean requiresResultSet)</code> so that 
-	 * reference to the created <code>RequestMessage</code> can be retained in 
-	 * the field <code>requestMessage</code>. 
-	 */
-	class TestableMMPreparedStatement extends PreparedStatementImpl {
-		/**
-		 * Contains a reference to the <code>RequestMessage</code> created by 
-		 * a call to <code>createRequestMessage(String[] commands, 
-		 * boolean isBatchedCommand, Boolean requiresResultSet)</code>.  This
-		 * will allow easy access to the prepared statement's request message 
-		 * generated by a call to one of the statement's execute methods.
-		 */
-		public RequestMessage requestMessage;
-		@Override
-		protected RequestMessage createRequestMessage(String[] commands,
-				boolean isBatchedCommand, ResultsMode resultsMode) {
-			this.requestMessage = super
-					.createRequestMessage(commands, isBatchedCommand, resultsMode);
-			return this.requestMessage;
-		}
-
-		public TestableMMPreparedStatement(ConnectionImpl connection,
-				String sql, int resultSetType, int resultSetConcurrency)
-				throws SQLException {
-			super(connection, sql, resultSetType, resultSetConcurrency);
-		}
-		
-	}
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/jdbc/TestPreparedStatement.java (from rev 2802, trunk/client/src/test/java/org/teiid/jdbc/TestPreparedStatement.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/jdbc/TestPreparedStatement.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/jdbc/TestPreparedStatement.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,349 @@
+/*
+ * 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.jdbc;
+
+import static org.junit.Assert.*;
+
+import java.sql.Blob;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.TimeZone;
+
+import org.junit.Test;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+import org.teiid.client.DQP;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.client.RequestMessage.ResultsMode;
+import org.teiid.client.security.LogonResult;
+import org.teiid.client.util.ResultsFuture;
+import org.teiid.jdbc.ConnectionImpl;
+import org.teiid.jdbc.PreparedStatementImpl;
+import org.teiid.jdbc.TeiidSQLException;
+import org.teiid.net.ServerConnection;
+
+
+/**
+ * Test case to validate general operations on an <code>MMPreparedStatement
+ * </code> 
+ */
+public class TestPreparedStatement {
+
+	/**
+	 * Test that <code>MMPreparedStatement</code>'s <code>execute()</code> method
+	 * will throw a <code>MMSQLException</code> if a connection does not exist.
+	 * 
+	 * @throws Exception
+	 */
+	@Test(expected=TeiidSQLException.class) public void testUpdateException() throws Exception {
+		PreparedStatementImpl statement = getMMPreparedStatement("delete from table"); //$NON-NLS-1$
+		statement.execute();
+	}
+	
+	/**
+	 * Verify that the <code>executeBatch()</code> method of <code>
+	 * MMPreparedStatement</code> is resulting in the correct command, 
+	 * parameter values for each command of the batch, and the request type 
+	 * are being set in the request message that would normally be sent to the 
+	 * server.
+	 *   
+	 * @throws Exception
+	 */
+	@Test public void testBatchedUpdateExecution() throws Exception {
+		// Build up a fake connection instance for use with the prepared statement
+		ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
+		DQP dqp = Mockito.mock(DQP.class);
+		ServerConnection serverConn = Mockito.mock(ServerConnection.class);
+		LogonResult logonResult = Mockito.mock(LogonResult.class);
+		
+		// stub methods
+		Mockito.stub(conn.getServerConnection()).toReturn(serverConn);
+		Mockito.stub(serverConn.getLogonResult()).toReturn(logonResult);
+		Mockito.stub(logonResult.getTimeZone()).toReturn(TimeZone.getDefault());
+
+		// a dummy result message that is specific to this test case
+		ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>(); 
+		Mockito.stub(dqp.executeRequest(Matchers.anyLong(), (RequestMessage)Matchers.anyObject())).toReturn(results);
+		ResultsMessage rm = new ResultsMessage();
+		rm.setResults(new List<?>[] {Arrays.asList(0), Arrays.asList(0), Arrays.asList(0)});
+		rm.setUpdateResult(true);
+		results.getResultsReceiver().receiveResults(rm);
+		Mockito.stub(conn.getDQP()).toReturn(dqp);
+		
+		// some update SQL
+		String sqlCommand = "delete from table where col=?"; //$NON-NLS-1$
+		TestableMMPreparedStatement statement = (TestableMMPreparedStatement) getMMPreparedStatement(conn, sqlCommand);
+
+		ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(3);
+		// Add some batches and their parameter values
+		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(1) } ) ) );
+		statement.setInt(1, new Integer(1));
+		statement.addBatch();
+		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(2) } ) ) );
+		statement.setInt(1, new Integer(2));
+		statement.addBatch();
+		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(3) } ) ) );
+		statement.setInt(1, new Integer(3));
+		statement.addBatch();
+		
+		// execute the batch and verify that it matches our dummy results 
+		// message set earlier
+		assertTrue(Arrays.equals(new int[] {0, 0, 0}, statement.executeBatch()));
+		
+		// Now verify the statement's RequestMessage is what we expect 
+		assertEquals("Command does not match", sqlCommand, statement.requestMessage.getCommandString()); //$NON-NLS-1$
+		assertEquals("Parameter values do not match", expectedParameterValues, statement.requestMessage.getParameterValues()); //$NON-NLS-1$
+		assertTrue("RequestMessage.isBatchedUpdate should be true", statement.requestMessage.isBatchedUpdate()); //$NON-NLS-1$
+		assertFalse("RequestMessage.isCallableStatement should be false", statement.requestMessage.isCallableStatement()); //$NON-NLS-1$
+		assertTrue("RequestMessage.isPreparedStatement should be true", statement.requestMessage.isPreparedStatement()); //$NON-NLS-1$
+	}
+	
+	/**
+	 * Verify that the <code>clearBatch()</code> method of 
+	 * <code>MMPreparedStatement</code> is clearing the list of batched 
+	 * commands.
+	 * <p>
+	 * This is done by first adding command parameter values to the batch and 
+	 * then invoking the <code>clearBatch()</code> method.
+	 *   
+	 * @throws Exception
+	 */
+	@Test public void testClearBatch() throws Exception {
+		PreparedStatementImpl statement = getMMPreparedStatement("delete from table where col=?"); //$NON-NLS-1$
+		// Add some stuff
+		statement.setInt(1, new Integer(1));
+		statement.addBatch();
+		statement.setInt(1, new Integer(2));
+		statement.addBatch();
+		// Make sure something is really there
+		assertTrue("MMPreparedStatement.ParameterValuesList should not be empty", statement.getParameterValuesList().size() > 0); //$NON-NLS-1$
+		// Now clear it
+		statement.clearBatch();
+		assertTrue("MMPreparedStatement.ParameterValuesList should be empty", statement.getParameterValuesList().size() == 0); //$NON-NLS-1$
+	}
+
+	/**
+	 * Adds additional batches of command parameter values to a prepared 
+	 * statement after a previous list has been cleared.
+	 * <p>
+	 * This is done by first adding command parameter values to the batch and 
+	 * then invoking the <code>clearBatch()</code> method.  Then a different 
+	 * set of command parameter values are added to the existing batch command.
+	 * <p>
+	 * The expected result is the command parameter list for the batches will 
+	 * only reflect what was added after <code>clearBatch()</code> was invoked.  
+	 *   
+	 * @throws Exception
+	 */
+	@Test public void testClearBatchAddBatch() throws Exception {
+		PreparedStatementImpl statement = getMMPreparedStatement("delete from table where col=?"); //$NON-NLS-1$
+		
+		statement.setInt(1, new Integer(1));
+		statement.addBatch();
+		statement.setInt(1, new Integer(2));
+		statement.addBatch();
+		// Make sure something is really there
+		assertTrue("MMPreparedStatement.ParameterValuesList should not be empty", statement.getParameterValuesList().size() > 0); //$NON-NLS-1$
+		// Now clear it
+		statement.clearBatch();
+		// Make sure it is empty now
+		assertTrue("MMPreparedStatement.ParameterValuesList should be empty", statement.getParameterValuesList().size() == 0); //$NON-NLS-1$
+
+		ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(1);
+		
+		// Now add something for validation 
+		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(5) } ) ) );
+		statement.setInt(1, new Integer(5));
+		statement.addBatch();
+		assertEquals("MMPreparedStatement.ParameterValuesList does not match", expectedParameterValues, statement.getParameterValuesList()); //$NON-NLS-1$
+	}
+
+	/**
+	 * Test the <code>addBatch()</code> method of <code>MMPreparedStatement</code> 
+	 * to verify that the command parameter values of the batch are added to the 
+	 * command parameter values list.
+	 *   
+	 * @throws Exception
+	 */
+	@Test public void testAddBatch() throws Exception {
+		PreparedStatementImpl statement = getMMPreparedStatement("delete from table where col=?"); //$NON-NLS-1$
+
+		ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(1);
+		
+		// First we add a single batch 
+		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(1) } ) ) );
+		statement.setInt(1, new Integer(1));
+		statement.addBatch();
+		assertEquals("MMPreparedStatement.ParameterValuesList does not match", expectedParameterValues, statement.getParameterValuesList()); //$NON-NLS-1$
+
+		// Now add some more batches just for sanity sake
+		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(3) } ) ) );
+		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(5) } ) ) );
+		statement.setInt(1, new Integer(3));
+		statement.addBatch();
+		statement.setInt(1, new Integer(5));
+		statement.addBatch();
+		assertEquals("MMPreparedStatement.ParameterValuesList does not match", expectedParameterValues, statement.getParameterValuesList()); //$NON-NLS-1$
+	}
+
+	@Test public void testSetBlob() throws Exception {
+		PreparedStatementImpl stmt = getMMPreparedStatement("delete from table where col=?"); //$NON-NLS-1$
+		stmt.setBlob(1, (Blob)null);
+	}	
+	
+	/**
+	 * Test the <code>addBatch()</code> method of <code>MMPreparedStatement</code> 
+	 * using a batch with an empty parameter value list.  The test will verify 
+	 * no failures occur when there are no command parameter values defined 
+	 * when the <code>addBatch()</code> method is invoked.
+	 * <p>
+	 * It is valid to add an empty parameter value list to a batch list.
+	 * <p>
+	 * For example:
+	 * <p>
+	 * <code>PreparedStatement stmt = conn.prepareStatement(sql);<br \>
+	 *  stmt.addBatch();<br \>
+	 *  stmt.addBatch();<br \>
+	 *  stmt.executeBatch();</code>
+	 *   
+	 * @throws Exception
+	 */
+	@Test public void testAddBatchNoParameterValues() throws Exception {
+		PreparedStatementImpl statement = getMMPreparedStatement("delete from table where col=?"); //$NON-NLS-1$
+		
+		// This will hold our expected values list
+		ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(1);
+		
+		// First batch has an empty parameter value list
+		expectedParameterValues.add( new ArrayList<Object>(Collections.emptyList()) );
+
+		// No values have been set  so we are adding a batch with an empty 
+		// parameter value list
+		statement.addBatch();
+
+		// Second batch contains a parameter value list
+		expectedParameterValues.add( new ArrayList<Object>( Arrays.asList( new Object[] { new Integer(1) } ) ) );
+
+		// We now are adding a batch that does have parameter values
+		statement.setInt(1, new Integer(1));
+		statement.addBatch();
+
+		// Check to see if our statement contains our expected parameter value list
+		assertEquals("MMPreparedStatement.ParameterValuesList does not match", expectedParameterValues, statement.getParameterValuesList()); //$NON-NLS-1$
+	}
+
+	/**
+	 * A helper method to get an <code>MMPreparedStatement</code> that can be 
+	 * used for simple test cases.
+	 * <p>
+	 * The returned value is an instance of <code>TestableMMPreparedStatement</code>
+	 * <p>
+	 * This method invokes <code>getMMPreparedStatement(final MMConnection conn, 
+	 * final String sql)</code> with a fake connection object constructed by 
+	 * <code>Mockito</code>.
+	 *   
+	 * @param sql the query for the prepared statement
+	 * @return an instance of TestableMMPreparedStatement
+	 * @throws SQLException
+	 */
+	protected PreparedStatementImpl getMMPreparedStatement(final String sql) throws SQLException {
+		ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
+		ServerConnection serverConn = Mockito.mock(ServerConnection.class);
+		LogonResult logonResult = Mockito.mock(LogonResult.class);
+		
+		Mockito.stub(conn.getServerConnection()).toReturn(serverConn);
+		Mockito.stub(serverConn.getLogonResult()).toReturn(logonResult);
+		Mockito.stub(logonResult.getTimeZone()).toReturn(TimeZone.getDefault());
+
+		return getMMPreparedStatement(conn, sql);
+	}
+	
+	/**
+	 * A helper method to get an <code>MMPreparedStatement</code> that can be 
+	 * used for simple test cases.
+	 * <p>
+	 * The returned value is an instance of <code>TestableMMPreparedStatement</code>
+	 * <p>
+	 * <code>conn</code> should be a valid instance of <code>MMConnection</code> 
+	 * or this method will fail.
+	 * 
+	 * @param conn an instance of <code>MMConnection</code>
+	 * @param sql the query for the prepared statement
+	 * @return an instance of TestableMMPreparedStatement
+	 * @throws SQLException
+	 */
+	protected PreparedStatementImpl getMMPreparedStatement(final ConnectionImpl conn, final String sql) throws SQLException {
+		TestableMMPreparedStatement statement = new TestableMMPreparedStatement(conn, sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+		
+		// Make sure everything is empty on start
+		assertTrue("MMPreparedStatement.ParameterValuesList should be empty", statement.getParameterValuesList().size() == 0); //$NON-NLS-1$
+		assertTrue("MMPreparedStatement.ParameterValues should be empty", statement.getParameterValues().size() == 0); //$NON-NLS-1$
+
+		return statement;
+	}
+	
+	/**
+	 * Represents an extension to <code>MMPreparedStatement</code> that 
+	 * gives access to the <code>RequestMessage</code> that is passed 
+	 * around inside <code>MMPreparedStatement</code>. 
+	 * <p>
+	 * This extension simply adds a field named <code>requestMessage</code> 
+	 * which is <code>public</code>.  This field gets set when the <code>protected</code>
+	 * method <code>createRequestMessage()</code> is called.
+	 * <p>
+	 * This extension also overrides <code>RequestMessage createRequestMessage(String[] commands,
+	 *			boolean isBatchedCommand, Boolean requiresResultSet)</code> so that 
+	 * reference to the created <code>RequestMessage</code> can be retained in 
+	 * the field <code>requestMessage</code>. 
+	 */
+	class TestableMMPreparedStatement extends PreparedStatementImpl {
+		/**
+		 * Contains a reference to the <code>RequestMessage</code> created by 
+		 * a call to <code>createRequestMessage(String[] commands, 
+		 * boolean isBatchedCommand, Boolean requiresResultSet)</code>.  This
+		 * will allow easy access to the prepared statement's request message 
+		 * generated by a call to one of the statement's execute methods.
+		 */
+		public RequestMessage requestMessage;
+		@Override
+		protected RequestMessage createRequestMessage(String[] commands,
+				boolean isBatchedCommand, ResultsMode resultsMode) {
+			this.requestMessage = super
+					.createRequestMessage(commands, isBatchedCommand, resultsMode);
+			return this.requestMessage;
+		}
+
+		public TestableMMPreparedStatement(ConnectionImpl connection,
+				String sql, int resultSetType, int resultSetConcurrency)
+				throws SQLException {
+			super(connection, sql, resultSetType, resultSetConcurrency);
+		}
+		
+	}
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/netty/handler/codec/serialization/TestObjectDecoderInputStream.java
===================================================================
--- trunk/client/src/test/java/org/teiid/netty/handler/codec/serialization/TestObjectDecoderInputStream.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/netty/handler/codec/serialization/TestObjectDecoderInputStream.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,79 +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.netty.handler.codec.serialization;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.SocketTimeoutException;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-public class TestObjectDecoderInputStream {
-
-	@Test public void testTimeoutException() throws Exception {
-		ByteArrayOutputStream baos = new ByteArrayOutputStream();
-		ObjectEncoderOutputStream oeos = new ObjectEncoderOutputStream(new DataOutputStream(baos), 512);
-		List<Integer> obj = Arrays.asList(1, 2, 3);
-		oeos.writeObject(obj);
-		oeos.close();
-		final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
-		InputStream is = new InputStream() {
-			int count;
-			@Override
-			public int read() throws IOException {
-				if (count++%2==0) { 
-					throw new SocketTimeoutException();
-				}
-				return bais.read();
-			}
-		};
-		ObjectDecoderInputStream odis = new ObjectDecoderInputStream(new DataInputStream(is), Thread.currentThread().getContextClassLoader(), 1024);
-		Object result = null;
-		do {
-			try {
-				result = odis.readObject();
-			} catch (IOException e) {
-				
-			}
-		} while (result == null);
-		assertEquals(obj, result);
-	}
-	
-	@Test public void testLargeIntConversion() throws Exception {
-		int testValue = 204503404;
-		ByteArrayOutputStream baos = new ByteArrayOutputStream();
-		DataOutputStream dos = new DataOutputStream(baos);
-		dos.writeInt(testValue);
-		dos.close();
-		assertEquals(testValue, ObjectDecoderInputStream.getIntFromBytes(baos.toByteArray()));
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/netty/handler/codec/serialization/TestObjectDecoderInputStream.java (from rev 2802, trunk/client/src/test/java/org/teiid/netty/handler/codec/serialization/TestObjectDecoderInputStream.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/netty/handler/codec/serialization/TestObjectDecoderInputStream.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/client/src/test/java/org/teiid/netty/handler/codec/serialization/TestObjectDecoderInputStream.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,104 @@
+/*
+ * 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.netty.handler.codec.serialization;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringReader;
+import java.net.SocketTimeoutException;
+import java.nio.charset.Charset;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.core.types.ClobImpl;
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.util.ReaderInputStream;
+
+import static org.junit.Assert.*;
+
+public class TestObjectDecoderInputStream {
+
+	@Test public void testTimeoutException() throws Exception {
+		ByteArrayOutputStream baos = new ByteArrayOutputStream();
+		ObjectEncoderOutputStream oeos = new ObjectEncoderOutputStream(new DataOutputStream(baos), 512);
+		List<Integer> obj = Arrays.asList(1, 2, 3);
+		oeos.writeObject(obj);
+		oeos.close();
+		final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+		InputStream is = new InputStream() {
+			int count;
+			@Override
+			public int read() throws IOException {
+				if (count++%2==0) { 
+					throw new SocketTimeoutException();
+				}
+				return bais.read();
+			}
+		};
+		ObjectDecoderInputStream odis = new ObjectDecoderInputStream(new DataInputStream(is), Thread.currentThread().getContextClassLoader(), 1024);
+		Object result = null;
+		do {
+			try {
+				result = odis.readObject();
+			} catch (IOException e) {
+				
+			}
+		} while (result == null);
+		assertEquals(obj, result);
+	}
+	
+	@Test public void testLargeIntConversion() throws Exception {
+		int testValue = 204503404;
+		ByteArrayOutputStream baos = new ByteArrayOutputStream();
+		DataOutputStream dos = new DataOutputStream(baos);
+		dos.writeInt(testValue);
+		dos.close();
+		assertEquals(testValue, ObjectDecoderInputStream.getIntFromBytes(baos.toByteArray()));
+	}
+	
+	
+	@Test public void testReplaceObject() throws Exception {
+		ByteArrayOutputStream baos = new ByteArrayOutputStream();
+		ObjectEncoderOutputStream out = new ObjectEncoderOutputStream(new DataOutputStream(baos), 512);
+		
+		ClobImpl clob = new ClobImpl(new InputStreamFactory() {
+			@Override
+			public InputStream getInputStream() throws IOException {
+				return new ReaderInputStream(new StringReader("Clob contents"),  Charset.forName(Streamable.ENCODING)); //$NON-NLS-1$
+			}
+			
+		}, -1);
+		
+		out.writeObject(clob);
+		
+		ObjectDecoderInputStream in = new ObjectDecoderInputStream(new DataInputStream(new ByteArrayInputStream(baos.toByteArray())), Thread.currentThread().getContextClassLoader(), 1024);
+		Object result = in.readObject();
+		assertTrue(result instanceof ClobImpl);
+	}	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/common-core/pom.xml
===================================================================
--- trunk/common-core/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/common-core/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/common-core/pom.xml (from rev 2804, trunk/common-core/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/common-core/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/common-core/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/common-core/src/main/java/org/teiid/core/types/InputStreamFactory.java
===================================================================
--- trunk/common-core/src/main/java/org/teiid/core/types/InputStreamFactory.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/types/InputStreamFactory.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,245 +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.core.types;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.nio.charset.Charset;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.SQLException;
-import java.sql.SQLXML;
-
-import javax.activation.DataSource;
-import javax.xml.transform.Source;
-
-import org.teiid.core.util.ReaderInputStream;
-
-public abstract class InputStreamFactory implements Source {
-	
-	public interface StreamFactoryReference {
-		
-		void setStreamFactory(InputStreamFactory inputStreamFactory);
-		
-	}
-	
-	private String systemId;
-	private long length = -1;
-	
-    /**
-     * Get a new InputStream
-     * @return
-     */
-    public abstract InputStream getInputStream() throws IOException;
-    
-    @Override
-    public String getSystemId() {
-    	return this.systemId;
-    }
-    
-    @Override
-    public void setSystemId(String systemId) {
-    	this.systemId = systemId;
-    }
-    
-    public void free() throws IOException {
-    	
-    }
-    
-    public long getLength() {
-		return length;
-	}
-    
-    public void setLength(long length) {
-		this.length = length;
-	}
-    
-    public Reader getCharacterStream() throws IOException {
-    	return null;
-    }
-    
-    public static class FileInputStreamFactory extends InputStreamFactory {
-    	
-    	private File f;
-    	
-    	public FileInputStreamFactory(File f) {
-    		this.f = f;
-    		this.setSystemId(f.toURI().toASCIIString());
-		}
-    	
-    	@Override
-    	public long getLength() {
-    		return f.length();
-    	}
-    	
-    	@Override
-    	public InputStream getInputStream() throws IOException {
-    		return new BufferedInputStream(new FileInputStream(f));
-    	}
-    	
-    }
-    
-    public static class ClobInputStreamFactory extends InputStreamFactory implements DataSource {
-    	
-    	private Clob clob;
-    	private Charset charset = Charset.forName(Streamable.ENCODING);
-    	
-    	public ClobInputStreamFactory(Clob clob) {
-    		this.clob = clob;
-    	}
-    	
-    	public Charset getCharset() {
-			return charset;
-		}
-    	
-    	public void setCharset(Charset charset) {
-			this.charset = charset;
-		}
-    	
-    	@Override
-    	public InputStream getInputStream() throws IOException {
-    		try {
-				return new ReaderInputStream(clob.getCharacterStream(), charset);
-			} catch (SQLException e) {
-				throw new IOException(e);
-			}
-    	}
-    	
-    	@Override
-    	public Reader getCharacterStream() throws IOException {
-    		try {
-				return clob.getCharacterStream();
-			} catch (SQLException e) {
-				throw new IOException(e);
-			}
-    	}
-
-		@Override
-		public String getContentType() {
-			return "text/plain"; //$NON-NLS-1$
-		}
-
-		@Override
-		public String getName() {
-			return "clob"; //$NON-NLS-1$
-		}
-
-		@Override
-		public OutputStream getOutputStream() throws IOException {
-			throw new UnsupportedOperationException();
-		}
-    	
-    }
-    
-    public static class BlobInputStreamFactory extends InputStreamFactory implements DataSource {
-    	
-    	private Blob blob;
-    	
-    	public BlobInputStreamFactory(Blob blob) {
-    		this.blob = blob;
-    	}
-    	
-    	@Override
-    	public InputStream getInputStream() throws IOException {
-    		try {
-				return blob.getBinaryStream();
-			} catch (SQLException e) {
-				throw new IOException(e);
-			}
-    	}
-    	
-    	@Override
-    	public long getLength() {
-    		try {
-				return blob.length();
-			} catch (SQLException e) {
-				return -1;
-			}
-    	}
-    	
-    	@Override
-		public String getContentType() {
-			return "application/octet-stream"; //$NON-NLS-1$
-		}
-
-		@Override
-		public String getName() {
-			return "blob"; //$NON-NLS-1$
-		}
-
-		@Override
-		public OutputStream getOutputStream() throws IOException {
-			throw new UnsupportedOperationException();
-		}
-    	
-    }
-    
-    public static class SQLXMLInputStreamFactory extends InputStreamFactory implements DataSource {
-    	
-    	private SQLXML sqlxml;
-    	
-    	public SQLXMLInputStreamFactory(SQLXML sqlxml) {
-    		this.sqlxml = sqlxml;
-    	}
-    	
-    	@Override
-    	public InputStream getInputStream() throws IOException {
-    		try {
-				return sqlxml.getBinaryStream();
-			} catch (SQLException e) {
-				throw new IOException(e);
-			}
-    	}
-    	
-    	@Override
-    	public Reader getCharacterStream() throws IOException {
-    		try {
-				return sqlxml.getCharacterStream();
-			} catch (SQLException e) {
-				throw new IOException(e);
-			}
-    	}
-    	
-    	@Override
-		public String getContentType() {
-			return "application/xml"; //$NON-NLS-1$
-		}
-
-		@Override
-		public String getName() {
-			return "sqlxml"; //$NON-NLS-1$
-		}
-
-		@Override
-		public OutputStream getOutputStream() throws IOException {
-			throw new UnsupportedOperationException();
-		}
-    	
-    }
-    
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/types/InputStreamFactory.java (from rev 2803, trunk/common-core/src/main/java/org/teiid/core/types/InputStreamFactory.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/types/InputStreamFactory.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/types/InputStreamFactory.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,254 @@
+/*
+ * 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.core.types;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.nio.charset.Charset;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+
+import javax.activation.DataSource;
+import javax.xml.transform.Source;
+
+import org.teiid.core.util.ReaderInputStream;
+
+public abstract class InputStreamFactory implements Source {
+	
+	public interface StreamFactoryReference {
+		
+		void setStreamFactory(InputStreamFactory inputStreamFactory);
+		
+	}
+	
+	private String systemId;
+	private long length = -1;
+	
+    /**
+     * Get a new InputStream
+     * @return
+     */
+    public abstract InputStream getInputStream() throws IOException;
+    
+    @Override
+    public String getSystemId() {
+    	return this.systemId;
+    }
+    
+    @Override
+    public void setSystemId(String systemId) {
+    	this.systemId = systemId;
+    }
+    
+    public void free() throws IOException {
+    	
+    }
+    
+    public long getLength() {
+		return length;
+	}
+    
+    public void setLength(long length) {
+		this.length = length;
+	}
+    
+    public Reader getCharacterStream() throws IOException {
+    	return null;
+    }
+    
+    public boolean isPersistent() {
+    	return false;
+    }
+    
+    public static class FileInputStreamFactory extends InputStreamFactory {
+    	
+    	private File f;
+    	
+    	public FileInputStreamFactory(File f) {
+    		this.f = f;
+    		this.setSystemId(f.toURI().toASCIIString());
+		}
+    	
+    	@Override
+    	public long getLength() {
+    		return f.length();
+    	}
+    	
+    	@Override
+    	public InputStream getInputStream() throws IOException {
+    		return new BufferedInputStream(new FileInputStream(f));
+    	}
+    	
+    	@Override
+    	public boolean isPersistent() {
+    		return true;
+    	}
+    	
+    }
+    
+    public static class ClobInputStreamFactory extends InputStreamFactory implements DataSource {
+    	
+    	private Clob clob;
+    	private Charset charset = Charset.forName(Streamable.ENCODING);
+    	
+    	public ClobInputStreamFactory(Clob clob) {
+    		this.clob = clob;
+    	}
+    	
+    	public Charset getCharset() {
+			return charset;
+		}
+    	
+    	public void setCharset(Charset charset) {
+			this.charset = charset;
+		}
+    	
+    	@Override
+    	public InputStream getInputStream() throws IOException {
+    		try {
+				return new ReaderInputStream(clob.getCharacterStream(), charset);
+			} catch (SQLException e) {
+				throw new IOException(e);
+			}
+    	}
+    	
+    	@Override
+    	public Reader getCharacterStream() throws IOException {
+    		try {
+				return clob.getCharacterStream();
+			} catch (SQLException e) {
+				throw new IOException(e);
+			}
+    	}
+
+		@Override
+		public String getContentType() {
+			return "text/plain"; //$NON-NLS-1$
+		}
+
+		@Override
+		public String getName() {
+			return "clob"; //$NON-NLS-1$
+		}
+
+		@Override
+		public OutputStream getOutputStream() throws IOException {
+			throw new UnsupportedOperationException();
+		}
+    	
+    }
+    
+    public static class BlobInputStreamFactory extends InputStreamFactory implements DataSource {
+    	
+    	private Blob blob;
+    	
+    	public BlobInputStreamFactory(Blob blob) {
+    		this.blob = blob;
+    	}
+    	
+    	@Override
+    	public InputStream getInputStream() throws IOException {
+    		try {
+				return blob.getBinaryStream();
+			} catch (SQLException e) {
+				throw new IOException(e);
+			}
+    	}
+    	
+    	@Override
+    	public long getLength() {
+    		try {
+				return blob.length();
+			} catch (SQLException e) {
+				return -1;
+			}
+    	}
+    	
+    	@Override
+		public String getContentType() {
+			return "application/octet-stream"; //$NON-NLS-1$
+		}
+
+		@Override
+		public String getName() {
+			return "blob"; //$NON-NLS-1$
+		}
+
+		@Override
+		public OutputStream getOutputStream() throws IOException {
+			throw new UnsupportedOperationException();
+		}
+    	
+    }
+    
+    public static class SQLXMLInputStreamFactory extends InputStreamFactory implements DataSource {
+    	
+    	private SQLXML sqlxml;
+    	
+    	public SQLXMLInputStreamFactory(SQLXML sqlxml) {
+    		this.sqlxml = sqlxml;
+    	}
+    	
+    	@Override
+    	public InputStream getInputStream() throws IOException {
+    		try {
+				return sqlxml.getBinaryStream();
+			} catch (SQLException e) {
+				throw new IOException(e);
+			}
+    	}
+    	
+    	@Override
+    	public Reader getCharacterStream() throws IOException {
+    		try {
+				return sqlxml.getCharacterStream();
+			} catch (SQLException e) {
+				throw new IOException(e);
+			}
+    	}
+    	
+    	@Override
+		public String getContentType() {
+			return "application/xml"; //$NON-NLS-1$
+		}
+
+		@Override
+		public String getName() {
+			return "sqlxml"; //$NON-NLS-1$
+		}
+
+		@Override
+		public OutputStream getOutputStream() throws IOException {
+			throw new UnsupportedOperationException();
+		}
+    	
+    }
+    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java
===================================================================
--- trunk/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.core.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.sql.SQLException;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-import org.teiid.core.CorePlugin;
-import org.teiid.core.TeiidException;
-
-
-public class ObjectConverterUtil {
-    
-    private static final int DEFAULT_READING_SIZE = 8192;
-
-     protected static byte[] convertBlobToByteArray(final java.sql.Blob data) throws TeiidException {
-          try {
-              // Open a stream to read the BLOB data
-              InputStream l_blobStream = data.getBinaryStream();
-              return convertToByteArray(l_blobStream);
-          } catch (IOException ioe) {
-                final Object[] params = new Object[]{data.getClass().getName()};
-                throw new TeiidException(ioe,CorePlugin.Util.getString("ObjectConverterUtil.Error_translating_results_from_data_type_to_a_byte[]._1",params)); //$NON-NLS-1$
-          } catch (SQLException sqe) {
-                final Object[] params = new Object[]{data.getClass().getName()};
-                throw new TeiidException(sqe,CorePlugin.Util.getString("ObjectConverterUtil.Error_translating_results_from_data_type_to_a_byte[]._2",params)); //$NON-NLS-1$
-          }
-    }
-
-    public static byte[] convertToByteArray(final Object data) throws TeiidException, IOException {
-        if (data instanceof InputStream) {
-            return convertToByteArray((InputStream) data);
-        } else if (data instanceof byte[]) {
-            return (byte[]) data;
-        } else if (data instanceof java.sql.Blob)  {
-            return convertBlobToByteArray((java.sql.Blob) data);
-        } else if (data instanceof File) {
-        	return convertFileToByteArray((File)data);
-        }
-        final Object[] params = new Object[]{data.getClass().getName()};
-        throw new TeiidException(CorePlugin.Util.getString("ObjectConverterUtil.Object_type_not_supported_for_object_conversion._3",params)); //$NON-NLS-1$
-    }
-
-    public static byte[] convertToByteArray(final InputStream is) throws IOException {
-    	return convertToByteArray(is, -1);
-    }
-    	
-    /**
-     * Returns the given input stream's contents as a byte array.
-     * If a length is specified (ie. if length != -1), only length bytes
-     * are returned. Otherwise all bytes in the stream are returned.
-     * Note this does close the stream, even if not all bytes are written, 
-     * because the buffering does not guarantee the end position.
-     * @throws IOException if a problem occurred reading the stream.
-     */
-    public static byte[] convertToByteArray(final InputStream is, int length) throws IOException {
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        write(out, is, length);
-        return out.toByteArray();
-    }
-    
-    public static void write(final OutputStream out, final InputStream is, int length) throws IOException {
-    	int writen = 0;
-        try {
-	        byte[] l_buffer = new byte[DEFAULT_READING_SIZE]; // buffer holding bytes to be transferred
-	        int l_nbytes = 0;  // Number of bytes read
-	        while ((l_nbytes = is.read(l_buffer)) != -1) {
-	        	if (length != -1 && writen > length - l_nbytes) {
-		        	out.write(l_buffer, 0, writen + l_nbytes - length); 
-		        	break;
-	        	}
-	        	out.write(l_buffer,0,l_nbytes); 
-	        	writen += l_nbytes;
-	        }
-        } finally {
-        	try {
-        		is.close();
-        	} finally {
-        		out.close();
-        	}
-        }
-    }
-    
-    public static void write(final Writer out, final Reader is, int length) throws IOException {
-    	int writen = 0;
-        try {
-	        char[] l_buffer = new char[DEFAULT_READING_SIZE]; // buffer holding bytes to be transferred
-	        int l_nbytes = 0;  // Number of bytes read
-	        while ((l_nbytes = is.read(l_buffer)) != -1) {
-	        	if (length != -1 && writen > length - l_nbytes) {
-		        	out.write(l_buffer, 0, writen + l_nbytes - length); 
-		        	break;
-	        	}
-	        	out.write(l_buffer,0,l_nbytes); 
-	        	writen += l_nbytes;
-	        }
-        } finally {
-        	try {
-        		is.close();
-        	} finally {
-        		out.close();
-        	}
-        }
-    }
-
-    public static InputStream convertToInputStream(byte[] data) {
-        ByteArrayInputStream bais = new ByteArrayInputStream(data);
-        InputStream isContent = new BufferedInputStream(bais);
-        return isContent;
-    }
-
-    public static InputStream convertToInputStream(final String data) {
-        return convertToInputStream(data.getBytes());
-    }
-    
-    public static InputStream convertToInputStream(final char[] data) {
-        return convertToInputStream(new String(data));
-    }
-
-    public static void write(final InputStream is, final String fileName) throws IOException {
-        File f = new File(fileName);
-        write(is, f);
-    }
-    
-    public static void write(final Reader reader, final String fileName) throws IOException {
-        File f = new File(fileName);
-        write(reader, f);
-    }    
-    
-    public static void write(final Reader reader, final File f) throws IOException {
-    	f.getParentFile().mkdirs();
-    	FileWriter fw = new FileWriter(f);        
-        write(fw, reader, -1);   
-    }
-
-    public static void write(final InputStream is, final File f) throws IOException {
-    	f.getParentFile().mkdirs();
-        FileOutputStream fio = new FileOutputStream(f);
-        BufferedOutputStream bos = new BufferedOutputStream(fio);
-    	write(bos, is, -1);
-    }
-    
-    public static void write(byte[] data, final String fileName) throws Exception {
-        InputStream is = ObjectConverterUtil.convertToInputStream(data);
-        ObjectConverterUtil.write(is, fileName);
-        is.close();
-    }
-    
-    public static void write(char[] data, final String fileName) throws Exception {
-        InputStream is = ObjectConverterUtil.convertToInputStream(data);
-        ObjectConverterUtil.write(is, fileName);
-        is.close();
-    }
-
-    /**
-     * Returns the given bytes as a char array using a given encoding (null means platform default).
-     */
-    public static char[] bytesToChar(byte[] bytes, String encoding) throws IOException {
-
-        return convertToCharArray(new ByteArrayInputStream(bytes), bytes.length, encoding);
-
-    }
-    /**
-     * Returns the contents of the given file as a byte array.
-     * @throws IOException if a problem occurred reading the file.
-     */
-    public static byte[] convertFileToByteArray(File file) throws IOException {
-        return convertToByteArray(new FileInputStream(file), (int) file.length());
-    }
-
-    /**
-     * Returns the contents of the given file as a char array.
-     * When encoding is null, then the platform default one is used
-     * @throws IOException if a problem occurred reading the file.
-     */
-    public static char[] convertFileToCharArray(File file, String encoding) throws IOException {
-        InputStream stream = new FileInputStream(file);
-        return convertToCharArray(stream, (int) file.length(), encoding);
-    }
-    
-    /**
-     * Returns the contents of the given file as a string.
-     * @throws IOException if a problem occurred reading the file.
-     */
-    public static String convertFileToString(final File file) throws IOException {
-        return new String(convertFileToCharArray(file,null));
-    }
-
-    
-    /**
-     * Returns the contents of the given InputStream as a string.
-     * @throws IOException if a problem occurred reading the file.
-     */
-    public static String convertToString(final InputStream stream) throws IOException {
-        return new String(convertToCharArray(stream, -1, null));
-    }
-    
-    /**
-     * Returns the given input stream's contents as a character array.
-     * If a length is specified (ie. if length != -1), only length chars
-     * are returned. Otherwise all chars in the stream are returned.
-     * Note this doesn't close the stream.
-     * @throws IOException if a problem occurred reading the stream.
-     */
-    public static char[] convertToCharArray(InputStream stream, int length, String encoding)
-        throws IOException {
-    	Reader r = null;
-    	if (encoding == null) {
-    		r = new InputStreamReader(stream);
-    	} else {
-    		r = new InputStreamReader(stream, encoding);
-    	}
-        return convertToCharArray(r, length);
-    }
-    
-    /**
-     * Returns the contents of the given zip entry as a byte array.
-     * @throws IOException if a problem occurred reading the zip entry.
-     */
-    public static byte[] convertToByteArray(ZipEntry ze, ZipFile zip)
-        throws IOException {
-        return convertToByteArray(zip.getInputStream(ze), (int) ze.getSize());
-    }
-    
-    public static String convertToString(Reader reader) throws IOException {
-    	return new String(convertToCharArray(reader, Integer.MAX_VALUE));
-    }
-
-    public static char[] convertToCharArray(Reader reader, int length) throws IOException {
-        StringWriter sb = new StringWriter();     
-        write(sb, reader, length);
-        return sb.toString().toCharArray();
-    }
-
-} 

Copied: tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java (from rev 2803, trunk/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,274 @@
+/*
+ * 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.core.util;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.sql.SQLException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.teiid.core.CorePlugin;
+import org.teiid.core.TeiidException;
+
+
+public class ObjectConverterUtil {
+    
+    private static final int DEFAULT_READING_SIZE = 8192;
+
+     protected static byte[] convertBlobToByteArray(final java.sql.Blob data) throws TeiidException {
+          try {
+              // Open a stream to read the BLOB data
+              InputStream l_blobStream = data.getBinaryStream();
+              return convertToByteArray(l_blobStream);
+          } catch (IOException ioe) {
+                final Object[] params = new Object[]{data.getClass().getName()};
+                throw new TeiidException(ioe,CorePlugin.Util.getString("ObjectConverterUtil.Error_translating_results_from_data_type_to_a_byte[]._1",params)); //$NON-NLS-1$
+          } catch (SQLException sqe) {
+                final Object[] params = new Object[]{data.getClass().getName()};
+                throw new TeiidException(sqe,CorePlugin.Util.getString("ObjectConverterUtil.Error_translating_results_from_data_type_to_a_byte[]._2",params)); //$NON-NLS-1$
+          }
+    }
+
+    public static byte[] convertToByteArray(final Object data) throws TeiidException, IOException {
+        if (data instanceof InputStream) {
+            return convertToByteArray((InputStream) data);
+        } else if (data instanceof byte[]) {
+            return (byte[]) data;
+        } else if (data instanceof java.sql.Blob)  {
+            return convertBlobToByteArray((java.sql.Blob) data);
+        } else if (data instanceof File) {
+        	return convertFileToByteArray((File)data);
+        }
+        final Object[] params = new Object[]{data.getClass().getName()};
+        throw new TeiidException(CorePlugin.Util.getString("ObjectConverterUtil.Object_type_not_supported_for_object_conversion._3",params)); //$NON-NLS-1$
+    }
+
+    public static byte[] convertToByteArray(final InputStream is) throws IOException {
+    	return convertToByteArray(is, -1);
+    }
+    	
+    /**
+     * Returns the given input stream's contents as a byte array.
+     * If a length is specified (ie. if length != -1), only length bytes
+     * are returned. Otherwise all bytes in the stream are returned.
+     * Note this does close the stream, even if not all bytes are written, 
+     * because the buffering does not guarantee the end position.
+     * @throws IOException if a problem occurred reading the stream.
+     */
+    public static byte[] convertToByteArray(final InputStream is, int length) throws IOException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        write(out, is, length);
+        return out.toByteArray();
+    }
+    
+    public static void write(final OutputStream out, final InputStream is, byte[] l_buffer, int length) throws IOException {
+    	int writen = 0;
+        try {
+	        int l_nbytes = 0;  // Number of bytes read
+	        while ((l_nbytes = is.read(l_buffer)) != -1) {
+	        	if (length != -1 && writen > length - l_nbytes) {
+		        	out.write(l_buffer, 0, writen + l_nbytes - length); 
+		        	break;
+	        	}
+	        	out.write(l_buffer,0,l_nbytes); 
+	        	writen += l_nbytes;
+	        }
+        } finally {
+        	try {
+        		is.close();
+        	} finally {
+        		out.close();
+        	}
+        }
+    }
+    
+    public static void write(final OutputStream out, final InputStream is, int length) throws IOException {
+    	write(out, is, new byte[DEFAULT_READING_SIZE], length); // buffer holding bytes to be transferred
+    }
+    
+    public static void write(final Writer out, final Reader is, int length) throws IOException {
+    	int writen = 0;
+        try {
+	        char[] l_buffer = new char[DEFAULT_READING_SIZE]; // buffer holding bytes to be transferred
+	        int l_nbytes = 0;  // Number of bytes read
+	        while ((l_nbytes = is.read(l_buffer)) != -1) {
+	        	if (length != -1 && writen > length - l_nbytes) {
+		        	out.write(l_buffer, 0, writen + l_nbytes - length); 
+		        	break;
+	        	}
+	        	out.write(l_buffer,0,l_nbytes); 
+	        	writen += l_nbytes;
+	        }
+        } finally {
+        	try {
+        		is.close();
+        	} finally {
+        		out.close();
+        	}
+        }
+    }
+
+    public static InputStream convertToInputStream(byte[] data) {
+        ByteArrayInputStream bais = new ByteArrayInputStream(data);
+        InputStream isContent = new BufferedInputStream(bais);
+        return isContent;
+    }
+
+    public static InputStream convertToInputStream(final String data) {
+        return convertToInputStream(data.getBytes());
+    }
+    
+    public static InputStream convertToInputStream(final char[] data) {
+        return convertToInputStream(new String(data));
+    }
+
+    public static void write(final InputStream is, final String fileName) throws IOException {
+        File f = new File(fileName);
+        write(is, f);
+    }
+    
+    public static void write(final Reader reader, final String fileName) throws IOException {
+        File f = new File(fileName);
+        write(reader, f);
+    }    
+    
+    public static void write(final Reader reader, final File f) throws IOException {
+    	f.getParentFile().mkdirs();
+    	FileWriter fw = new FileWriter(f);        
+        write(fw, reader, -1);   
+    }
+
+    public static void write(final InputStream is, final File f) throws IOException {
+    	f.getParentFile().mkdirs();
+        FileOutputStream fio = new FileOutputStream(f);
+        BufferedOutputStream bos = new BufferedOutputStream(fio);
+    	write(bos, is, -1);
+    }
+    
+    public static void write(byte[] data, final String fileName) throws Exception {
+        InputStream is = ObjectConverterUtil.convertToInputStream(data);
+        ObjectConverterUtil.write(is, fileName);
+        is.close();
+    }
+    
+    public static void write(char[] data, final String fileName) throws Exception {
+        InputStream is = ObjectConverterUtil.convertToInputStream(data);
+        ObjectConverterUtil.write(is, fileName);
+        is.close();
+    }
+
+    /**
+     * Returns the given bytes as a char array using a given encoding (null means platform default).
+     */
+    public static char[] bytesToChar(byte[] bytes, String encoding) throws IOException {
+
+        return convertToCharArray(new ByteArrayInputStream(bytes), bytes.length, encoding);
+
+    }
+    /**
+     * Returns the contents of the given file as a byte array.
+     * @throws IOException if a problem occurred reading the file.
+     */
+    public static byte[] convertFileToByteArray(File file) throws IOException {
+        return convertToByteArray(new FileInputStream(file), (int) file.length());
+    }
+
+    /**
+     * Returns the contents of the given file as a char array.
+     * When encoding is null, then the platform default one is used
+     * @throws IOException if a problem occurred reading the file.
+     */
+    public static char[] convertFileToCharArray(File file, String encoding) throws IOException {
+        InputStream stream = new FileInputStream(file);
+        return convertToCharArray(stream, (int) file.length(), encoding);
+    }
+    
+    /**
+     * Returns the contents of the given file as a string.
+     * @throws IOException if a problem occurred reading the file.
+     */
+    public static String convertFileToString(final File file) throws IOException {
+        return new String(convertFileToCharArray(file,null));
+    }
+
+    
+    /**
+     * Returns the contents of the given InputStream as a string.
+     * @throws IOException if a problem occurred reading the file.
+     */
+    public static String convertToString(final InputStream stream) throws IOException {
+        return new String(convertToCharArray(stream, -1, null));
+    }
+    
+    /**
+     * Returns the given input stream's contents as a character array.
+     * If a length is specified (ie. if length != -1), only length chars
+     * are returned. Otherwise all chars in the stream are returned.
+     * Note this doesn't close the stream.
+     * @throws IOException if a problem occurred reading the stream.
+     */
+    public static char[] convertToCharArray(InputStream stream, int length, String encoding)
+        throws IOException {
+    	Reader r = null;
+    	if (encoding == null) {
+    		r = new InputStreamReader(stream);
+    	} else {
+    		r = new InputStreamReader(stream, encoding);
+    	}
+        return convertToCharArray(r, length);
+    }
+    
+    /**
+     * Returns the contents of the given zip entry as a byte array.
+     * @throws IOException if a problem occurred reading the zip entry.
+     */
+    public static byte[] convertToByteArray(ZipEntry ze, ZipFile zip)
+        throws IOException {
+        return convertToByteArray(zip.getInputStream(ze), (int) ze.getSize());
+    }
+    
+    public static String convertToString(Reader reader) throws IOException {
+    	return new String(convertToCharArray(reader, Integer.MAX_VALUE));
+    }
+
+    public static char[] convertToCharArray(Reader reader, int length) throws IOException {
+        StringWriter sb = new StringWriter();     
+        write(sb, reader, length);
+        return sb.toString().toCharArray();
+    }
+
+} 

Deleted: tags/teiid-parent-7.3.0.Alpha2/connectors/connector-file/pom.xml
===================================================================
--- trunk/connectors/connector-file/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-file/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/connector-file/pom.xml (from rev 2804, trunk/connectors/connector-file/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/connector-file/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-file/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/connector-ldap/pom.xml
===================================================================
--- trunk/connectors/connector-ldap/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ldap/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/connector-ldap/pom.xml (from rev 2804, trunk/connectors/connector-ldap/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ldap/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ldap/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/connector-salesforce/pom.xml
===================================================================
--- trunk/connectors/connector-salesforce/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/connector-salesforce/pom.xml (from rev 2804, trunk/connectors/connector-salesforce/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,385 +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.resource.adapter.salesforce;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import javax.resource.ResourceException;
-import javax.xml.datatype.XMLGregorianCalendar;
-import javax.xml.ws.BindingProvider;
-
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.resource.spi.BasicConnection;
-import org.teiid.translator.salesforce.SalesforceConnection;
-import org.teiid.translator.salesforce.execution.DataPayload;
-import org.teiid.translator.salesforce.execution.DeletedObject;
-import org.teiid.translator.salesforce.execution.DeletedResult;
-import org.teiid.translator.salesforce.execution.UpdatedResult;
-
-import com.sforce.soap.partner.CallOptions;
-import com.sforce.soap.partner.DeleteResult;
-import com.sforce.soap.partner.DeletedRecord;
-import com.sforce.soap.partner.DescribeGlobalResult;
-import com.sforce.soap.partner.DescribeSObjectResult;
-import com.sforce.soap.partner.GetDeletedResult;
-import com.sforce.soap.partner.GetUpdatedResult;
-import com.sforce.soap.partner.InvalidFieldFault;
-import com.sforce.soap.partner.InvalidIdFault;
-import com.sforce.soap.partner.LoginFault;
-import com.sforce.soap.partner.LoginResult;
-import com.sforce.soap.partner.MalformedQueryFault;
-import com.sforce.soap.partner.MruHeader;
-import com.sforce.soap.partner.ObjectFactory;
-import com.sforce.soap.partner.PackageVersionHeader;
-import com.sforce.soap.partner.QueryOptions;
-import com.sforce.soap.partner.QueryResult;
-import com.sforce.soap.partner.SaveResult;
-import com.sforce.soap.partner.SessionHeader;
-import com.sforce.soap.partner.SforceService;
-import com.sforce.soap.partner.Soap;
-import com.sforce.soap.partner.sobject.SObject;
-
-public class SalesforceConnectionImpl extends BasicConnection implements SalesforceConnection {
-	private SforceService sfService;
-	private Soap sfSoap;
-	private SessionHeader sh;
-	private CallOptions co;
-	
-	private ObjectFactory partnerFactory = new ObjectFactory();
-	
-	PackageVersionHeader pvHeader = partnerFactory.createPackageVersionHeader();
-	
-	public SalesforceConnectionImpl(String username, String password, URL url) throws ResourceException {
-		login(username, password, url);
-	}
-	
-	String getUserName() throws ResourceException {
-			try {
-				return sfSoap.getUserInfo(sh).getUserName();
-			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-				throw new ResourceException(e.getMessage());
-			}
-	}
-	
-	Soap getBinding() {
-		return sfSoap;
-	}
-	
-	private void login(String username, String password, URL url) throws ResourceException {
-		if (!isValid()) {
-			LoginResult loginResult = null;
-			sfSoap = null;
-			sfService = null;
-			co = new CallOptions();
-			// This value identifies Teiid as a SF certified solution.
-			// It was provided by SF and should not be changed.
-			co.setClient("RedHat/MetaMatrix/"); //$NON-NLS-1$
-			
-			if(url == null) {
-				throw new ResourceException("SalesForce URL is not specified, please provide a valid URL"); //$NON-NLS-1$
-			}
-
-			try {
-				sfService = new SforceService();
-				sfSoap = sfService.getSoap();
-				((BindingProvider)sfSoap).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toExternalForm());
-				loginResult = sfSoap.login(username, password);
-			} catch (LoginFault e) {
-				throw new ResourceException(e.getCause().getMessage());
-			} catch (InvalidIdFault e) {
-				throw new ResourceException(e.getCause().getMessage());
-			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-				throw new ResourceException(e.getCause().getMessage());
-			}
-			LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Login was successful for username " + username); //$NON-NLS-1$
-
-			sh = new SessionHeader();
-			sh.setSessionId(loginResult.getSessionId());
-			// Reset the SOAP endpoint to the returned server URL
-			((BindingProvider)sfSoap).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,loginResult.getServerUrl());
-			// or maybe org.apache.cxf.message.Message.ENDPOINT_ADDRESS
-			((BindingProvider)sfSoap).getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY,Boolean.TRUE);
-			// Set the timeout.
-			//((BindingProvider)sfSoap).getRequestContext().put(JAXWSProperties.CONNECT_TIMEOUT, timeout);
-
-			
-			// Test the connection.
-			try {
-				sfSoap.getUserInfo(sh);
-			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-				throw new ResourceException(e.getMessage());
-			}
-		}
-	}
-	
-	
-	public boolean isValid() {
-		boolean result = true;
-		if(sfSoap == null) {
-			result = false;
-		} else {
-			try {
-				sfSoap.getServerTimestamp(sh);
-			} catch (Throwable t) {
-				LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Caught Throwable in isAlive", t); //$NON-NLS-1$
-				result = false;
-			}
-		}
-		return result;
-	}
-
-	public QueryResult query(String queryString, int batchSize, Boolean queryAll) throws ResourceException {
-		
-		if(batchSize > 2000) {
-			batchSize = 2000;
-			LogManager.logDetail(LogConstants.CTX_CONNECTOR, "reduced.batch.size"); //$NON-NLS-1$
-		}
-		
-		QueryResult qr = null;
-		QueryOptions qo = partnerFactory.createQueryOptions();
-		qo.setBatchSize(batchSize);
-		try {
-			if(queryAll) {
-				qr = sfSoap.queryAll(queryString, sh);
-			} else {
-				MruHeader mruHeader = partnerFactory.createMruHeader();
-				mruHeader.setUpdateMru(false);
-				
-				qr = sfSoap.query(queryString, sh);
-			}
-		} catch (InvalidFieldFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (MalformedQueryFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (InvalidIdFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.InvalidQueryLocatorFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		}
-		return qr;
-	}
-
-	public QueryResult queryMore(String queryLocator, int batchSize) throws ResourceException {
-		QueryOptions qo = partnerFactory.createQueryOptions();
-		qo.setBatchSize(batchSize);
-		try {
-			return sfSoap.queryMore(queryLocator, sh);
-		} catch (InvalidFieldFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.InvalidQueryLocatorFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		}
-		
-	}
-
-	public int delete(String[] ids) throws ResourceException {
-		List<DeleteResult> results = null;
-		try {
-			results = sfSoap.delete(Arrays.asList(ids), sh);
-		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		}
-		
-		boolean allGood = true;
-		StringBuffer errorMessages = new StringBuffer();
-		for(int i = 0; i < results.size(); i++) {
-			DeleteResult result = results.get(i);
-			if(!result.isSuccess()) {
-				if(allGood) {
-					errorMessages.append("Error(s) executing DELETE: "); //$NON-NLS-1$
-					allGood = false;
-				}
-				List<com.sforce.soap.partner.Error> errors = result.getErrors();
-				if(null != errors && errors.size() > 0) {
-					for(int x = 0; x < errors.size(); x++) {
-						com.sforce.soap.partner.Error error = errors.get(x);
-						errorMessages.append(error.getMessage()).append(';');
-					}
-				}
-				
-			}
-		}
-		if(!allGood) {
-			throw new ResourceException(errorMessages.toString());
-		}
-		return results.size();
-	}
-
-	public int create(DataPayload data) throws ResourceException {
-		SObject toCreate = new SObject();
-		toCreate.setType(data.getType());
-		toCreate.getAny().addAll(data.getMessageElements());
-		List<SObject> objects = new ArrayList<SObject>();
-		objects.add(toCreate);
-		List<SaveResult> result;
-		try {
-			result = sfSoap.create(objects, sh);
-		} catch (InvalidFieldFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (InvalidIdFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		}
-		return analyzeResult(result);
-	}
-
-	public int update(List<DataPayload> updateDataList) throws ResourceException {
-		List<SObject> params = new ArrayList<SObject>(updateDataList.size());
-		for(int i = 0; i < updateDataList.size(); i++) {
-			DataPayload data = updateDataList.get(i);
-			SObject toCreate = new SObject();
-			toCreate.setType(data.getType());
-			toCreate.setId(data.getID());
-			toCreate.getAny().addAll(data.getMessageElements());
-			params.add(i, toCreate);
-		}
-		List<SaveResult> result;
-			try {
-				result = sfSoap.update(params, sh);
-			} catch (InvalidFieldFault e) {
-				throw new ResourceException(e.getMessage(),e);
-			} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
-				throw new ResourceException(e.getMessage(),e);
-			} catch (InvalidIdFault e) {
-				throw new ResourceException(e.getMessage(),e);
-			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-				throw new ResourceException(e.getMessage(),e);
-			}
-		return analyzeResult(result);
-	}
-	
-	private int analyzeResult(List<SaveResult> results) throws ResourceException {
-		for (SaveResult result : results) {
-			if(!result.isSuccess()) {
-				throw new ResourceException(result.getErrors().get(0).getMessage());
-			}
-		}
-		return results.size();
-	}
-
-	public UpdatedResult getUpdated(String objectType, XMLGregorianCalendar startDate, XMLGregorianCalendar endDate) throws ResourceException {
-			GetUpdatedResult updated;
-			try {
-				updated = sfSoap.getUpdated(objectType, startDate, endDate, sh);
-			} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
-				throw new ResourceException(e.getMessage(), e);
-			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-				throw new ResourceException(e.getMessage(), e);
-			}
-			UpdatedResult result = new UpdatedResult(); 
-			result.setLatestDateCovered(updated.getLatestDateCovered().toGregorianCalendar());
-			result.setIDs(updated.getIds());
-			return result;
-	}
-
-	public DeletedResult getDeleted(String objectName, XMLGregorianCalendar startCalendar,
-			XMLGregorianCalendar endCalendar) throws ResourceException {
-			GetDeletedResult deleted;
-			try {
-				deleted = sfSoap.getDeleted(objectName, startCalendar, endCalendar, sh);
-			} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
-				throw new ResourceException(e.getMessage(), e);
-			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-				throw new ResourceException(e.getMessage(), e);
-			}
-			DeletedResult result = new DeletedResult();
-			result.setLatestDateCovered(deleted.getLatestDateCovered().toGregorianCalendar());
-			result.setEarliestDateAvailable(deleted.getEarliestDateAvailable().toGregorianCalendar());
-			List<DeletedRecord> records = deleted.getDeletedRecords();
-			List<DeletedObject> resultRecords = new ArrayList<DeletedObject>();
-			DeletedObject object;
-			if(null !=records) {
-				for (DeletedObject record : resultRecords) {
-					object = new DeletedObject();
-					object.setID(record.getID());
-					object.setDeletedDate(record.getDeletedDate());
-					resultRecords.add(object);
-				}
-			}
-			result.setResultRecords(resultRecords);
-			return result;
-	}
-	
-	public  QueryResult retrieve(String fieldList, String sObjectType, List<String> ids) throws ResourceException {
-		try {
-			List<SObject> objects = sfSoap.retrieve(fieldList, sObjectType, ids, sh);
-			QueryResult result = new QueryResult();
-			result.getRecords().addAll(objects);
-			result.setSize(objects.size());
-			return result;			
-		} catch (InvalidFieldFault e) {
-			throw new ResourceException(e.getMessage(),e);
-		} catch (MalformedQueryFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (InvalidIdFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-			throw new ResourceException(e.getMessage(),e);
-		}
-		
-	}
-
-	public DescribeGlobalResult getObjects() throws ResourceException {
-		try {
-			return sfSoap.describeGlobal(sh);
-		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-			ResourceException ce = new ResourceException(e.getCause().getMessage());
-			ce.initCause(e.getCause());
-			throw ce;
-		}
-	}
-
-	public DescribeSObjectResult getObjectMetaData(String objectName) throws ResourceException {
-		try {
-			return sfSoap.describeSObject(objectName, sh);
-		} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
-			throw new ResourceException(e.getMessage(), e);
-		}
-	}
-
-	@Override
-	public void close() throws ResourceException {
-		
-	}
-	
-	@Override
-	public boolean isAlive() {
-		return isValid();
-	}	
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java (from rev 2802, trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,385 @@
+/*
+ * 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.resource.adapter.salesforce;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.resource.ResourceException;
+import javax.xml.datatype.XMLGregorianCalendar;
+import javax.xml.ws.BindingProvider;
+
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.spi.BasicConnection;
+import org.teiid.translator.salesforce.SalesforceConnection;
+import org.teiid.translator.salesforce.execution.DataPayload;
+import org.teiid.translator.salesforce.execution.DeletedObject;
+import org.teiid.translator.salesforce.execution.DeletedResult;
+import org.teiid.translator.salesforce.execution.UpdatedResult;
+
+import com.sforce.soap.partner.CallOptions;
+import com.sforce.soap.partner.DeleteResult;
+import com.sforce.soap.partner.DeletedRecord;
+import com.sforce.soap.partner.DescribeGlobalResult;
+import com.sforce.soap.partner.DescribeSObjectResult;
+import com.sforce.soap.partner.GetDeletedResult;
+import com.sforce.soap.partner.GetUpdatedResult;
+import com.sforce.soap.partner.InvalidFieldFault;
+import com.sforce.soap.partner.InvalidIdFault;
+import com.sforce.soap.partner.LoginFault;
+import com.sforce.soap.partner.LoginResult;
+import com.sforce.soap.partner.MalformedQueryFault;
+import com.sforce.soap.partner.MruHeader;
+import com.sforce.soap.partner.ObjectFactory;
+import com.sforce.soap.partner.PackageVersionHeader;
+import com.sforce.soap.partner.QueryOptions;
+import com.sforce.soap.partner.QueryResult;
+import com.sforce.soap.partner.SaveResult;
+import com.sforce.soap.partner.SessionHeader;
+import com.sforce.soap.partner.SforceService;
+import com.sforce.soap.partner.Soap;
+import com.sforce.soap.partner.sobject.SObject;
+
+public class SalesforceConnectionImpl extends BasicConnection implements SalesforceConnection {
+	private SforceService sfService;
+	private Soap sfSoap;
+	private SessionHeader sh;
+	private CallOptions co;
+	
+	private ObjectFactory partnerFactory = new ObjectFactory();
+	
+	PackageVersionHeader pvHeader = partnerFactory.createPackageVersionHeader();
+	
+	public SalesforceConnectionImpl(String username, String password, URL url) throws ResourceException {
+		login(username, password, url);
+	}
+	
+	String getUserName() throws ResourceException {
+			try {
+				return sfSoap.getUserInfo(sh).getUserName();
+			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+				throw new ResourceException(e);
+			}
+	}
+	
+	Soap getBinding() {
+		return sfSoap;
+	}
+	
+	private void login(String username, String password, URL url) throws ResourceException {
+		if (!isValid()) {
+			LoginResult loginResult = null;
+			sfSoap = null;
+			sfService = null;
+			co = new CallOptions();
+			// This value identifies Teiid as a SF certified solution.
+			// It was provided by SF and should not be changed.
+			co.setClient("RedHat/MetaMatrix/"); //$NON-NLS-1$
+			
+			if(url == null) {
+				throw new ResourceException("SalesForce URL is not specified, please provide a valid URL"); //$NON-NLS-1$
+			}
+
+			try {
+				sfService = new SforceService();
+				sfSoap = sfService.getSoap();
+				((BindingProvider)sfSoap).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toExternalForm());
+				loginResult = sfSoap.login(username, password);
+			} catch (LoginFault e) {
+				throw new ResourceException(e);
+			} catch (InvalidIdFault e) {
+				throw new ResourceException(e);
+			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+				throw new ResourceException(e);
+			}
+			LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Login was successful for username " + username); //$NON-NLS-1$
+
+			sh = new SessionHeader();
+			sh.setSessionId(loginResult.getSessionId());
+			// Reset the SOAP endpoint to the returned server URL
+			((BindingProvider)sfSoap).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,loginResult.getServerUrl());
+			// or maybe org.apache.cxf.message.Message.ENDPOINT_ADDRESS
+			((BindingProvider)sfSoap).getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY,Boolean.TRUE);
+			// Set the timeout.
+			//((BindingProvider)sfSoap).getRequestContext().put(JAXWSProperties.CONNECT_TIMEOUT, timeout);
+
+			
+			// Test the connection.
+			try {
+				sfSoap.getUserInfo(sh);
+			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+				throw new ResourceException(e);
+			}
+		}
+	}
+	
+	
+	public boolean isValid() {
+		boolean result = true;
+		if(sfSoap == null) {
+			result = false;
+		} else {
+			try {
+				sfSoap.getServerTimestamp(sh);
+			} catch (Throwable t) {
+				LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Caught Throwable in isAlive", t); //$NON-NLS-1$
+				result = false;
+			}
+		}
+		return result;
+	}
+
+	public QueryResult query(String queryString, int batchSize, Boolean queryAll) throws ResourceException {
+		
+		if(batchSize > 2000) {
+			batchSize = 2000;
+			LogManager.logDetail(LogConstants.CTX_CONNECTOR, "reduced.batch.size"); //$NON-NLS-1$
+		}
+		
+		QueryResult qr = null;
+		QueryOptions qo = partnerFactory.createQueryOptions();
+		qo.setBatchSize(batchSize);
+		try {
+			if(queryAll) {
+				qr = sfSoap.queryAll(queryString, sh);
+			} else {
+				MruHeader mruHeader = partnerFactory.createMruHeader();
+				mruHeader.setUpdateMru(false);
+				
+				qr = sfSoap.query(queryString, sh);
+			}
+		} catch (InvalidFieldFault e) {
+			throw new ResourceException(e);
+		} catch (MalformedQueryFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+			throw new ResourceException(e);
+		} catch (InvalidIdFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.InvalidQueryLocatorFault e) {
+			throw new ResourceException(e);
+		}
+		return qr;
+	}
+
+	public QueryResult queryMore(String queryLocator, int batchSize) throws ResourceException {
+		QueryOptions qo = partnerFactory.createQueryOptions();
+		qo.setBatchSize(batchSize);
+		try {
+			return sfSoap.queryMore(queryLocator, sh);
+		} catch (InvalidFieldFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.InvalidQueryLocatorFault e) {
+			throw new ResourceException(e);
+		}
+		
+	}
+
+	public int delete(String[] ids) throws ResourceException {
+		List<DeleteResult> results = null;
+		try {
+			results = sfSoap.delete(Arrays.asList(ids), sh);
+		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+			throw new ResourceException(e);
+		}
+		
+		boolean allGood = true;
+		StringBuffer errorMessages = new StringBuffer();
+		for(int i = 0; i < results.size(); i++) {
+			DeleteResult result = results.get(i);
+			if(!result.isSuccess()) {
+				if(allGood) {
+					errorMessages.append("Error(s) executing DELETE: "); //$NON-NLS-1$
+					allGood = false;
+				}
+				List<com.sforce.soap.partner.Error> errors = result.getErrors();
+				if(null != errors && errors.size() > 0) {
+					for(int x = 0; x < errors.size(); x++) {
+						com.sforce.soap.partner.Error error = errors.get(x);
+						errorMessages.append(error.getMessage()).append(';');
+					}
+				}
+				
+			}
+		}
+		if(!allGood) {
+			throw new ResourceException(errorMessages.toString());
+		}
+		return results.size();
+	}
+
+	public int create(DataPayload data) throws ResourceException {
+		SObject toCreate = new SObject();
+		toCreate.setType(data.getType());
+		toCreate.getAny().addAll(data.getMessageElements());
+		List<SObject> objects = new ArrayList<SObject>();
+		objects.add(toCreate);
+		List<SaveResult> result;
+		try {
+			result = sfSoap.create(objects, sh);
+		} catch (InvalidFieldFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+			throw new ResourceException(e);
+		} catch (InvalidIdFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+			throw new ResourceException(e);
+		}
+		return analyzeResult(result);
+	}
+
+	public int update(List<DataPayload> updateDataList) throws ResourceException {
+		List<SObject> params = new ArrayList<SObject>(updateDataList.size());
+		for(int i = 0; i < updateDataList.size(); i++) {
+			DataPayload data = updateDataList.get(i);
+			SObject toCreate = new SObject();
+			toCreate.setType(data.getType());
+			toCreate.setId(data.getID());
+			toCreate.getAny().addAll(data.getMessageElements());
+			params.add(i, toCreate);
+		}
+		List<SaveResult> result;
+			try {
+				result = sfSoap.update(params, sh);
+			} catch (InvalidFieldFault e) {
+				throw new ResourceException(e);
+			} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+				throw new ResourceException(e);
+			} catch (InvalidIdFault e) {
+				throw new ResourceException(e);
+			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+				throw new ResourceException(e);
+			}
+		return analyzeResult(result);
+	}
+	
+	private int analyzeResult(List<SaveResult> results) throws ResourceException {
+		for (SaveResult result : results) {
+			if(!result.isSuccess()) {
+				throw new ResourceException(result.getErrors().get(0).getMessage());
+			}
+		}
+		return results.size();
+	}
+
+	public UpdatedResult getUpdated(String objectType, XMLGregorianCalendar startDate, XMLGregorianCalendar endDate) throws ResourceException {
+			GetUpdatedResult updated;
+			try {
+				updated = sfSoap.getUpdated(objectType, startDate, endDate, sh);
+			} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+				throw new ResourceException(e);
+			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+				throw new ResourceException(e);
+			}
+			UpdatedResult result = new UpdatedResult(); 
+			result.setLatestDateCovered(updated.getLatestDateCovered().toGregorianCalendar());
+			result.setIDs(updated.getIds());
+			return result;
+	}
+
+	public DeletedResult getDeleted(String objectName, XMLGregorianCalendar startCalendar,
+			XMLGregorianCalendar endCalendar) throws ResourceException {
+			GetDeletedResult deleted;
+			try {
+				deleted = sfSoap.getDeleted(objectName, startCalendar, endCalendar, sh);
+			} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+				throw new ResourceException(e);
+			} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+				throw new ResourceException(e);
+			}
+			DeletedResult result = new DeletedResult();
+			result.setLatestDateCovered(deleted.getLatestDateCovered().toGregorianCalendar());
+			result.setEarliestDateAvailable(deleted.getEarliestDateAvailable().toGregorianCalendar());
+			List<DeletedRecord> records = deleted.getDeletedRecords();
+			List<DeletedObject> resultRecords = new ArrayList<DeletedObject>();
+			DeletedObject object;
+			if(null !=records) {
+				for (DeletedObject record : resultRecords) {
+					object = new DeletedObject();
+					object.setID(record.getID());
+					object.setDeletedDate(record.getDeletedDate());
+					resultRecords.add(object);
+				}
+			}
+			result.setResultRecords(resultRecords);
+			return result;
+	}
+	
+	public  QueryResult retrieve(String fieldList, String sObjectType, List<String> ids) throws ResourceException {
+		try {
+			List<SObject> objects = sfSoap.retrieve(fieldList, sObjectType, ids, sh);
+			QueryResult result = new QueryResult();
+			result.getRecords().addAll(objects);
+			result.setSize(objects.size());
+			result.setDone(true);
+			return result;			
+		} catch (InvalidFieldFault e) {
+			throw new ResourceException(e);
+		} catch (MalformedQueryFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+			throw new ResourceException(e);
+		} catch (InvalidIdFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+			throw new ResourceException(e);
+		}
+		
+	}
+
+	public DescribeGlobalResult getObjects() throws ResourceException {
+		try {
+			return sfSoap.describeGlobal(sh);
+		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+			throw new ResourceException(e);
+		}
+	}
+
+	public DescribeSObjectResult getObjectMetaData(String objectName) throws ResourceException {
+		try {
+			return sfSoap.describeSObject(objectName, sh);
+		} catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+			throw new ResourceException(e);
+		} catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+			throw new ResourceException(e);
+		}
+	}
+
+	@Override
+	public void close() throws ResourceException {
+		
+	}
+	
+	@Override
+	public boolean isAlive() {
+		return isValid();
+	}	
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ws/pom.xml
===================================================================
--- trunk/connectors/connector-ws/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ws/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/connector-ws/pom.xml (from rev 2804, trunk/connectors/connector-ws/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ws/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/connector-ws/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/pom.xml
===================================================================
--- trunk/connectors/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,95 +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.3.0.Alpha2-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>translator-delegate</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.3.0.Alpha2/connectors/pom.xml (from rev 2804, trunk/connectors/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,95 @@
+<?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.3.0.Alpha2</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>translator-delegate</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.3.0.Alpha2/connectors/salesforce-api/pom.xml
===================================================================
--- trunk/connectors/salesforce-api/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/salesforce-api/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/salesforce-api/pom.xml (from rev 2804, trunk/connectors/salesforce-api/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/salesforce-api/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/salesforce-api/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/sandbox/pom.xml
===================================================================
--- trunk/connectors/sandbox/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/sandbox/pom.xml (from rev 2804, trunk/connectors/sandbox/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/sandbox/translator-yahoo/pom.xml
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/translator-yahoo/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/sandbox/translator-yahoo/pom.xml (from rev 2804, trunk/connectors/sandbox/translator-yahoo/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/translator-yahoo/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/sandbox/translator-yahoo/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/translator-delegate/pom.xml
===================================================================
--- trunk/connectors/translator-delegate/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-delegate/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>translator-delegate</artifactId>
-    <groupId>org.jboss.teiid.connectors</groupId>
-    <name>Delegate Translator</name>
-    <description>Delegate 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.3.0.Alpha2/connectors/translator-delegate/pom.xml (from rev 2804, trunk/connectors/translator-delegate/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-delegate/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-delegate/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>translator-delegate</artifactId>
+    <groupId>org.jboss.teiid.connectors</groupId>
+    <name>Delegate Translator</name>
+    <description>Delegate 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.3.0.Alpha2/connectors/translator-file/pom.xml
===================================================================
--- trunk/connectors/translator-file/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-file/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/translator-file/pom.xml (from rev 2804, trunk/connectors/translator-file/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-file/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-file/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/translator-jdbc/pom.xml
===================================================================
--- trunk/connectors/translator-jdbc/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-jdbc/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/translator-jdbc/pom.xml (from rev 2804, trunk/connectors/translator-jdbc/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-jdbc/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-jdbc/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/translator-ldap/pom.xml
===================================================================
--- trunk/connectors/translator-ldap/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ldap/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/translator-ldap/pom.xml (from rev 2804, trunk/connectors/translator-ldap/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ldap/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ldap/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/translator-loopback/pom.xml
===================================================================
--- trunk/connectors/translator-loopback/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-loopback/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/translator-loopback/pom.xml (from rev 2804, trunk/connectors/translator-loopback/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-loopback/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-loopback/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/translator-salesforce/pom.xml
===================================================================
--- trunk/connectors/translator-salesforce/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/translator-salesforce/pom.xml (from rev 2804, trunk/connectors/translator-salesforce/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/Util.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/Util.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/Util.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,71 +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;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-
-import org.teiid.translator.TranslatorException;
-
-
-public class Util {
-
-	public static String stripQutes(String id) {
-		if((id.startsWith("'") && id.endsWith("'"))) { //$NON-NLS-1$ //$NON-NLS-2$
-			id = id.substring(1,id.length()-1);
-		} else if ((id.startsWith("\"") && id.endsWith("\""))) { //$NON-NLS-1$ //$NON-NLS-2$
-			id = id.substring(1,id.length()-1);
-		}
-		return id;
-	}
-	
-	public static String addSingleQuotes(String text) {
-		StringBuffer result = new StringBuffer();
-		if(!text.startsWith("'")) { //$NON-NLS-1$
-			result.append('\'');
-		}
-		result.append(text);
-		if(!text.endsWith("'")) { //$NON-NLS-1$
-			result.append('\'');
-		} 
-		return result.toString();
-	}
-	
-	public static void validateQueryLength(StringBuffer query) throws TranslatorException {
-		if(query.length() >= 10000) {
-			throw new TranslatorException(SalesForcePlugin.Util.getString("Util.query.exceeds.max.length")); //$NON-NLS-1$
-		}
-	}
-
-	public static SimpleDateFormat getSalesforceDateTimeFormat() {
-			return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //$NON-NLS-1$
-	}
-	
-	public static SimpleDateFormat getTimeZoneOffsetFormat() {
-		return new SimpleDateFormat("Z"); //$NON-NLS-1$
-	}
-
-	public static DateFormat getSalesforceDateFormat() {
-		return new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/Util.java (from rev 2802, trunk/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/Util.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/Util.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/Util.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,71 @@
+/*
+ * 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;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+import org.teiid.translator.TranslatorException;
+
+
+public class Util {
+
+	public static String stripQutes(String id) {
+		if((id.startsWith("'") && id.endsWith("'"))) { //$NON-NLS-1$ //$NON-NLS-2$
+			id = id.substring(1,id.length()-1);
+		} else if ((id.startsWith("\"") && id.endsWith("\""))) { //$NON-NLS-1$ //$NON-NLS-2$
+			id = id.substring(1,id.length()-1);
+		}
+		return id;
+	}
+	
+	public static String addSingleQuotes(String text) {
+		StringBuffer result = new StringBuffer();
+		if(!text.startsWith("'")) { //$NON-NLS-1$
+			result.append('\'');
+		}
+		result.append(text);
+		if(!text.endsWith("'")) { //$NON-NLS-1$
+			result.append('\'');
+		} 
+		return result.toString();
+	}
+	
+	public static void validateQueryLength(StringBuffer query) throws TranslatorException {
+		if(query.length() >= 10000) {
+			throw new TranslatorException(SalesForcePlugin.Util.getString("Util.query.exceeds.max.length")); //$NON-NLS-1$
+		}
+	}
+
+	public static SimpleDateFormat getSalesforceDateTimeFormat() {
+			return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); //$NON-NLS-1$
+	}
+	
+	public static SimpleDateFormat getTimeZoneOffsetFormat() {
+		return new SimpleDateFormat("Z"); //$NON-NLS-1$
+	}
+
+	public static DateFormat getSalesforceDateFormat() {
+		return new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/visitors/CriteriaVisitor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/visitors/CriteriaVisitor.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/visitors/CriteriaVisitor.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,452 +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.visitors;
-
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.language.AndOr;
-import org.teiid.language.ColumnReference;
-import org.teiid.language.Comparison;
-import org.teiid.language.Expression;
-import org.teiid.language.Function;
-import org.teiid.language.In;
-import org.teiid.language.Like;
-import org.teiid.language.Literal;
-import org.teiid.language.NamedTable;
-import org.teiid.language.Not;
-import org.teiid.language.Comparison.Operator;
-import org.teiid.language.visitor.HierarchyVisitor;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.RuntimeMetadata;
-import org.teiid.metadata.Table;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.salesforce.SalesForcePlugin;
-import org.teiid.translator.salesforce.Util;
-
-
-/**
- * Parses Criteria in support of all of the ExecutionImpl classes.
- */
-public abstract class CriteriaVisitor extends HierarchyVisitor implements ICriteriaVisitor {
-
-    private static final String RESTRICTEDMULTISELECTPICKLIST = "restrictedmultiselectpicklist"; //$NON-NLS-1$
-	private static final String MULTIPICKLIST = "multipicklist"; //$NON-NLS-1$
-	protected static final String SELECT = "SELECT"; //$NON-NLS-1$
-    protected static final String FROM = "FROM"; //$NON-NLS-1$
-    protected static final String WHERE = "WHERE"; //$NON-NLS-1$
-    protected static final String ORDER_BY = "ORDER BY"; //$NON-NLS-1$
-    protected static final String LIMIT = "LIMIT"; //$NON-NLS-1$
-    protected static final String SPACE = " "; //$NON-NLS-1$
-    protected static final String EXCLUDES = "EXCLUDES"; //$NON-NLS-1$
-    protected static final String INCLUDES = "includes"; //$NON-NLS-1$
-    protected static final String COMMA = ","; //$NON-NLS-1$
-    protected static final String SEMI = ";"; //$NON-NLS-1$
-    protected static final String APOS = "'"; //$NON-NLS-1$
-    protected static final String OPEN = "("; //$NON-NLS-1$
-    protected static final String CLOSE = ")"; //$NON-NLS-1$
-
-    protected RuntimeMetadata metadata;
-    private HashMap<Comparison.Operator, String> comparisonOperators;
-    protected List<String> criteriaList = new ArrayList<String>();
-    protected boolean hasCriteria;
-    protected Map<String, Column> columnElementsByName = new HashMap<String, Column>();
-    protected List<TranslatorException> exceptions = new ArrayList<TranslatorException>();
-    protected Table table;
-    boolean onlyIDCriteria;
-    protected Boolean queryAll = Boolean.FALSE;
-	
-    // support for invoking a retrieve when possible.
-    protected In idInCriteria = null;
-	
-
-    public CriteriaVisitor( RuntimeMetadata metadata ) {
-        this.metadata = metadata;
-        comparisonOperators = new HashMap<Comparison.Operator, String>();
-        comparisonOperators.put(Operator.EQ, "="); //$NON-NLS-1$
-        comparisonOperators.put(Operator.GE, ">="); //$NON-NLS-1$
-        comparisonOperators.put(Operator.GT, ">"); //$NON-NLS-1$
-        comparisonOperators.put(Operator.LE, "<="); //$NON-NLS-1$
-        comparisonOperators.put(Operator.LT, "<"); //$NON-NLS-1$
-        comparisonOperators.put(Operator.NE, "!="); //$NON-NLS-1$
-    }
-
-    @Override
-    public void visit( Comparison criteria ) {
-        super.visit(criteria);
-        try {
-            addCompareCriteria(criteriaList, criteria);
-            boolean isAcceptableID = (Operator.EQ == criteria.getOperator() && isIdColumn(criteria.getLeftExpression()));
-            setHasCriteria(true, isAcceptableID);
-        } catch (TranslatorException e) {
-            exceptions.add(e);
-        }
-    }
-
-    @Override
-    public void visit( Like criteria ) {
-        try {
-            if (isIdColumn(criteria.getLeftExpression())) {
-                TranslatorException e = new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.LIKE.not.supported.on.Id")); //$NON-NLS-1$
-                exceptions.add(e);
-            }
-            if (isMultiSelectColumn(criteria.getLeftExpression())) {
-                TranslatorException e = new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.LIKE.not.supported.on.multiselect")); //$NON-NLS-1$
-                exceptions.add(e);
-            }
-        } catch (TranslatorException e) {
-            exceptions.add(e);
-        }
-        boolean negated = criteria.isNegated();
-        criteria.setNegated(false);
-        criteriaList.add(criteria.toString());
-        if (negated) {
-        	addNot();
-        	criteria.setNegated(true);
-        }
-        // don't check if it's ID, Id LIKE '123%' still requires a query
-        setHasCriteria(true, false);
-    }
-    
-    @Override
-    public void visit(AndOr obj) {
-    	List<String> savedCriteria = new LinkedList<String>();
-    	savedCriteria.add(OPEN);
-		super.visitNode(obj.getLeftCondition());
-		savedCriteria.addAll(this.criteriaList);
-		this.criteriaList.clear();
-		savedCriteria.add(CLOSE);
-		savedCriteria.add(SPACE);
-		savedCriteria.add(obj.getOperator().toString());
-		savedCriteria.add(SPACE);
-		savedCriteria.add(OPEN);
-		super.visitNode(obj.getRightCondition());
-		savedCriteria.addAll(this.criteriaList);
-		this.criteriaList.clear();
-		this.criteriaList = savedCriteria;
-		this.criteriaList.add(CLOSE);
-    }
-    
-    @Override
-    public void visit(Not obj) {
-    	super.visit(obj);
-    	addNot();
-    }
-
-	private void addNot() {
-		if (!criteriaList.isEmpty()) {
-    		criteriaList.add(0, "NOT ("); //$NON-NLS-1$
-    		criteriaList.add(CLOSE);
-    	}
-	}
-
-    @Override
-    public void visit( In criteria ) {
-        try {
-            Expression lExpr = criteria.getLeftExpression();
-            if (lExpr instanceof ColumnReference) {
-            	ColumnReference cr = (ColumnReference)lExpr;
-                Column column = cr.getMetadataObject();
-                if (column != null && (MULTIPICKLIST.equalsIgnoreCase(column.getNativeType()) || RESTRICTEDMULTISELECTPICKLIST.equalsIgnoreCase(column.getNativeType()))) {
-                    appendMultiselectIn(column, criteria);
-                } else {
-                    appendCriteria(criteria);
-                }
-            } else {
-            	appendCriteria(criteria);
-            }
-            setHasCriteria(true, isIdColumn(criteria.getLeftExpression()));
-        } catch (TranslatorException e) {
-            exceptions.add(e);
-        }
-    }
-
-    public void parseFunction( Function func ) {
-        String functionName = func.getName();
-        try {
-            if (functionName.equalsIgnoreCase("includes")) { //$NON-NLS-1$
-                generateMultiSelect(func, INCLUDES);
-            } else if (functionName.equalsIgnoreCase("excludes")) { //$NON-NLS-1$
-                generateMultiSelect(func, EXCLUDES);
-            }
-        } catch (TranslatorException e) {
-            exceptions.add(e);
-        }
-    }
-
-    private void generateMultiSelect( Function func,
-                                      String funcName ) throws TranslatorException {
-        List<Expression> expressions = func.getParameters();
-        validateFunction(expressions);
-        Expression columnExpression = expressions.get(0);
-        Column column = ((ColumnReference)columnExpression).getMetadataObject();
-        StringBuffer criterion = new StringBuffer();
-        criterion.append(column.getNameInSource()).append(SPACE).append(funcName);
-        addFunctionParams((Literal)expressions.get(1), criterion);
-        criteriaList.add(criterion.toString());
-    }
-
-    private void appendMultiselectIn( Column column,
-                                      In criteria ) throws TranslatorException {
-        StringBuffer result = new StringBuffer();
-        result.append(column.getNameInSource()).append(SPACE);
-        if (criteria.isNegated()) {
-            result.append(EXCLUDES).append(SPACE);
-        } else {
-            result.append(INCLUDES).append(SPACE);
-        }
-        result.append('(');
-        List<Expression> rightExpressions = criteria.getRightExpressions();
-        Iterator<Expression> iter = rightExpressions.iterator();
-        boolean first = true;
-        while (iter.hasNext()) {
-            Expression rightExpression = iter.next();
-            if (first) {
-                result.append(rightExpression.toString());
-                first = false;
-            } else {
-                result.append(COMMA).append(rightExpression.toString());
-            }
-
-        }
-        result.append(')');
-        criteriaList.add(result.toString());
-    }
-
-    private void validateFunction( List<Expression> expressions ) throws TranslatorException {
-        if (expressions.size() != 2) {
-            throw new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.invalid.arg.count")); //$NON-NLS-1$
-        }
-        if (!(expressions.get(0) instanceof ColumnReference)) {
-            throw new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.function.not.column.arg")); //$NON-NLS-1$
-        }
-        if (!(expressions.get(1) instanceof Literal)) {
-            throw new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.function.not.literal.arg")); //$NON-NLS-1$
-        }
-    }
-
-    private void addFunctionParams( Literal param,
-                                    StringBuffer criterion ) {
-        criterion.append(OPEN);
-        boolean first = true;
-        String fullParam = param.toString();
-        String[] params = fullParam.split(","); //$NON-NLS-1$
-        for (int i = 0; i < params.length; i++) {
-            String token = params[i];
-            if (first) {
-                criterion.append(SPACE).append(Util.addSingleQuotes(token));
-                first = false;
-            } else {
-                criterion.append(COMMA).append(SPACE).append(Util.addSingleQuotes(token));
-            }
-        }
-        criterion.append(CLOSE);
-    }
-
-    protected void addCompareCriteria( List criteriaList,
-                                       Comparison compCriteria ) throws TranslatorException {
-        Expression lExpr = compCriteria.getLeftExpression();
-        if (lExpr instanceof Function) {
-            parseFunction((Function)lExpr);
-        } else {
-            ColumnReference left = (ColumnReference)lExpr;
-            Column column = left.getMetadataObject();
-            String columnName = column.getNameInSource();
-            StringBuffer queryString = new StringBuffer();
-            queryString.append(column.getParent().getNameInSource());
-            queryString.append('.');
-            queryString.append(columnName).append(SPACE);
-            queryString.append(comparisonOperators.get(compCriteria.getOperator()));
-            queryString.append(' ');
-            Expression rExp = compCriteria.getRightExpression();
-            if(rExp instanceof Literal) {
-            	Literal literal = (Literal)rExp;
-            	if (column.getJavaType().equals(Boolean.class)) {
-            		queryString.append(((Boolean)literal.getValue()).toString());
-            	} else if (column.getJavaType().equals(java.sql.Timestamp.class)) {
-            		Timestamp datetime = (java.sql.Timestamp)literal.getValue();
-            		String value = Util.getSalesforceDateTimeFormat().format(datetime);
-            		String zoneValue = Util.getTimeZoneOffsetFormat().format(datetime);
-            		queryString.append(value).append(zoneValue.subSequence(0, 3)).append(':').append(zoneValue.subSequence(3, 5));
-            	} else if (column.getJavaType().equals(java.sql.Time.class)) {
-            		String value = Util.getSalesforceDateTimeFormat().format((java.sql.Time)literal.getValue());
-            		queryString.append(value);
-            	} else if (column.getJavaType().equals(java.sql.Date.class)) {
-            		String value = Util.getSalesforceDateFormat().format((java.sql.Date)literal.getValue());
-            		queryString.append(value);
-            	} else {
-            		queryString.append(compCriteria.getRightExpression().toString());
-            	}
-            } else if(rExp instanceof ColumnReference) {
-            	ColumnReference right = (ColumnReference)lExpr;
-                column = left.getMetadataObject();
-                columnName = column.getNameInSource();
-                queryString.append(columnName);
-            }
-
-            criteriaList.add(queryString.toString());
-
-            if (columnName.equals("IsDeleted")) { //$NON-NLS-1$
-                Literal isDeletedLiteral = (Literal)compCriteria.getRightExpression();
-                Boolean isDeleted = (Boolean)isDeletedLiteral.getValue();
-                if (isDeleted) {
-                    this.queryAll = isDeleted;
-                }
-            }
-        }
-    }
-
-    private void appendCriteria( In criteria ) throws TranslatorException {
-        StringBuffer queryString = new StringBuffer();
-        Expression leftExp = criteria.getLeftExpression();
-        if(isIdColumn(leftExp)) {
-        	idInCriteria  = criteria;
-        }
-        queryString.append(getValue(leftExp));
-        queryString.append(' ');
-        if (criteria.isNegated()) {
-            queryString.append("NOT "); //$NON-NLS-1$
-        }
-        queryString.append("IN"); //$NON-NLS-1$
-        queryString.append('(');
-        Column column = ((ColumnReference)criteria.getLeftExpression()).getMetadataObject();
-        boolean timeColumn = isTimeColumn(column);
-        boolean first = true;
-        Iterator iter = criteria.getRightExpressions().iterator();
-        while (iter.hasNext()) {
-            if (!first) queryString.append(',');
-            if (!timeColumn) queryString.append('\'');
-            queryString.append(getValue((Expression)iter.next()));
-            if (!timeColumn) queryString.append('\'');
-            first = false;
-        }
-        queryString.append(')');
-        criteriaList.add(queryString.toString());
-    }
-
-    private boolean isTimeColumn( Column column ) throws TranslatorException {
-        boolean result = false;
-        if (column.getJavaType().equals(java.sql.Timestamp.class) || column.getJavaType().equals(java.sql.Time.class)
-            || column.getJavaType().equals(java.sql.Date.class)) {
-            result = true;
-        }
-        return result;
-    }
-
-    protected String getValue( Expression expr ) throws TranslatorException {
-        String result;
-        if (expr instanceof ColumnReference) {
-            ColumnReference element = (ColumnReference)expr;
-            Column element2 = element.getMetadataObject();
-            result = element2.getNameInSource();
-        } else if (expr instanceof Literal) {
-            Literal literal = (Literal)expr;
-            result = literal.getValue().toString();
-        } else {
-            throw new RuntimeException("unknown type in SalesforceQueryExecution.getValue(): " + expr.toString()); //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    protected void loadColumnMetadata( NamedTable group ) throws TranslatorException {
-        table = group.getMetadataObject();
-        String supportsQuery = table.getProperties().get("Supports Query"); //$NON-NLS-1$
-        if (!Boolean.valueOf(supportsQuery)) {
-            throw new TranslatorException(table.getNameInSource() + " " + SalesForcePlugin.Util.getString("CriteriaVisitor.query.not.supported")); //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        List<Column> columnIds = table.getColumns();
-        for (Column element : columnIds) {
-            // influences queryAll behavior
-            if (element.getNameInSource().equals("IsDeleted")) { //$NON-NLS-1$
-                String isDeleted = element.getDefaultValue();
-                if (Boolean.parseBoolean(isDeleted)) {
-                    this.queryAll = true;
-                }
-            }
-        }
-    }
-
-    protected boolean isIdColumn( Expression expression ) throws TranslatorException {
-        boolean result = false;
-        if (expression instanceof ColumnReference) {
-            Column element = ((ColumnReference)expression).getMetadataObject();
-            String nameInSource = element.getNameInSource();
-            if (nameInSource.equalsIgnoreCase("id")) { //$NON-NLS-1$
-                result = true;
-            }
-        }
-        return result;
-    }
-
-    protected boolean isMultiSelectColumn( Expression expression ) throws TranslatorException {
-        boolean result = false;
-        if (expression instanceof ColumnReference) {
-            Column element = ((ColumnReference)expression).getMetadataObject();
-            String nativeType = element.getNativeType();
-            if (MULTIPICKLIST.equalsIgnoreCase(nativeType) || RESTRICTEDMULTISELECTPICKLIST.equalsIgnoreCase(nativeType)) {
-                result = true;
-            }
-        }
-        return result;
-    }
-
-    public boolean hasCriteria() {
-        return hasCriteria;
-    }
-
-    public void setHasCriteria( boolean hasCriteria,
-                                boolean isIdCriteria ) {
-        if (isIdCriteria) {
-            if (hasCriteria()) {
-                this.onlyIDCriteria = false;
-            } else {
-                this.onlyIDCriteria = true;
-            }
-        } else if (this.onlyIDCriteria) {
-            this.onlyIDCriteria = false;
-        }
-        this.hasCriteria = hasCriteria;
-    }
-
-    public boolean hasOnlyIDCriteria() {
-        return this.onlyIDCriteria;
-    }
-
-    public String getTableName() throws TranslatorException {
-        return table.getNameInSource();
-    }
-    
-    protected void addCriteriaString(StringBuffer result) {
-    	if(hasCriteria()) {
-			result.append(WHERE).append(SPACE);
-			for (String string : criteriaList) {
-				result.append(string);
-			}
-			result.append(SPACE);
-		}
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/visitors/CriteriaVisitor.java (from rev 2802, trunk/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/visitors/CriteriaVisitor.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/visitors/CriteriaVisitor.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/execution/visitors/CriteriaVisitor.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,456 @@
+/*
+ * 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.visitors;
+
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.language.AndOr;
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Comparison;
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.In;
+import org.teiid.language.Like;
+import org.teiid.language.Literal;
+import org.teiid.language.NamedTable;
+import org.teiid.language.Not;
+import org.teiid.language.Comparison.Operator;
+import org.teiid.language.visitor.HierarchyVisitor;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.metadata.Table;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.salesforce.SalesForcePlugin;
+import org.teiid.translator.salesforce.Util;
+
+
+/**
+ * Parses Criteria in support of all of the ExecutionImpl classes.
+ */
+public abstract class CriteriaVisitor extends HierarchyVisitor implements ICriteriaVisitor {
+
+    private static final String RESTRICTEDMULTISELECTPICKLIST = "restrictedmultiselectpicklist"; //$NON-NLS-1$
+	private static final String MULTIPICKLIST = "multipicklist"; //$NON-NLS-1$
+	protected static final String SELECT = "SELECT"; //$NON-NLS-1$
+    protected static final String FROM = "FROM"; //$NON-NLS-1$
+    protected static final String WHERE = "WHERE"; //$NON-NLS-1$
+    protected static final String ORDER_BY = "ORDER BY"; //$NON-NLS-1$
+    protected static final String LIMIT = "LIMIT"; //$NON-NLS-1$
+    protected static final String SPACE = " "; //$NON-NLS-1$
+    protected static final String EXCLUDES = "EXCLUDES"; //$NON-NLS-1$
+    protected static final String INCLUDES = "includes"; //$NON-NLS-1$
+    protected static final String COMMA = ","; //$NON-NLS-1$
+    protected static final String SEMI = ";"; //$NON-NLS-1$
+    protected static final String APOS = "'"; //$NON-NLS-1$
+    protected static final String OPEN = "("; //$NON-NLS-1$
+    protected static final String CLOSE = ")"; //$NON-NLS-1$
+
+    protected RuntimeMetadata metadata;
+    private HashMap<Comparison.Operator, String> comparisonOperators;
+    protected List<String> criteriaList = new ArrayList<String>();
+    protected boolean hasCriteria;
+    protected Map<String, Column> columnElementsByName = new HashMap<String, Column>();
+    protected List<TranslatorException> exceptions = new ArrayList<TranslatorException>();
+    protected Table table;
+    boolean onlyIDCriteria;
+    protected Boolean queryAll = Boolean.FALSE;
+	
+    // support for invoking a retrieve when possible.
+    protected In idInCriteria = null;
+	
+
+    public CriteriaVisitor( RuntimeMetadata metadata ) {
+        this.metadata = metadata;
+        comparisonOperators = new HashMap<Comparison.Operator, String>();
+        comparisonOperators.put(Operator.EQ, "="); //$NON-NLS-1$
+        comparisonOperators.put(Operator.GE, ">="); //$NON-NLS-1$
+        comparisonOperators.put(Operator.GT, ">"); //$NON-NLS-1$
+        comparisonOperators.put(Operator.LE, "<="); //$NON-NLS-1$
+        comparisonOperators.put(Operator.LT, "<"); //$NON-NLS-1$
+        comparisonOperators.put(Operator.NE, "!="); //$NON-NLS-1$
+    }
+
+    @Override
+    public void visit( Comparison criteria ) {
+        super.visit(criteria);
+        try {
+            addCompareCriteria(criteriaList, criteria);
+            boolean isAcceptableID = (Operator.EQ == criteria.getOperator() && isIdColumn(criteria.getLeftExpression()));
+            setHasCriteria(true, isAcceptableID);
+            if (isAcceptableID) {
+            	this.idInCriteria = new In(criteria.getLeftExpression(), Arrays.asList(criteria.getRightExpression()), false);
+            }
+        } catch (TranslatorException e) {
+            exceptions.add(e);
+        }
+    }
+
+    @Override
+    public void visit( Like criteria ) {
+        try {
+            if (isIdColumn(criteria.getLeftExpression())) {
+                TranslatorException e = new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.LIKE.not.supported.on.Id")); //$NON-NLS-1$
+                exceptions.add(e);
+            }
+            if (isMultiSelectColumn(criteria.getLeftExpression())) {
+                TranslatorException e = new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.LIKE.not.supported.on.multiselect")); //$NON-NLS-1$
+                exceptions.add(e);
+            }
+        } catch (TranslatorException e) {
+            exceptions.add(e);
+        }
+        boolean negated = criteria.isNegated();
+        criteria.setNegated(false);
+        criteriaList.add(criteria.toString());
+        if (negated) {
+        	addNot();
+        	criteria.setNegated(true);
+        }
+        // don't check if it's ID, Id LIKE '123%' still requires a query
+        setHasCriteria(true, false);
+    }
+    
+    @Override
+    public void visit(AndOr obj) {
+    	List<String> savedCriteria = new LinkedList<String>();
+    	savedCriteria.add(OPEN);
+		super.visitNode(obj.getLeftCondition());
+		savedCriteria.addAll(this.criteriaList);
+		this.criteriaList.clear();
+		savedCriteria.add(CLOSE);
+		savedCriteria.add(SPACE);
+		savedCriteria.add(obj.getOperator().toString());
+		savedCriteria.add(SPACE);
+		savedCriteria.add(OPEN);
+		super.visitNode(obj.getRightCondition());
+		savedCriteria.addAll(this.criteriaList);
+		this.criteriaList.clear();
+		this.criteriaList = savedCriteria;
+		this.criteriaList.add(CLOSE);
+    }
+    
+    @Override
+    public void visit(Not obj) {
+    	super.visit(obj);
+    	addNot();
+    }
+
+	private void addNot() {
+		if (!criteriaList.isEmpty()) {
+    		criteriaList.add(0, "NOT ("); //$NON-NLS-1$
+    		criteriaList.add(CLOSE);
+    	}
+	}
+
+    @Override
+    public void visit( In criteria ) {
+        try {
+            Expression lExpr = criteria.getLeftExpression();
+            if (lExpr instanceof ColumnReference) {
+            	ColumnReference cr = (ColumnReference)lExpr;
+                Column column = cr.getMetadataObject();
+                if (column != null && (MULTIPICKLIST.equalsIgnoreCase(column.getNativeType()) || RESTRICTEDMULTISELECTPICKLIST.equalsIgnoreCase(column.getNativeType()))) {
+                    appendMultiselectIn(column, criteria);
+                } else {
+                    appendCriteria(criteria);
+                }
+            } else {
+            	appendCriteria(criteria);
+            }
+            setHasCriteria(true, isIdColumn(criteria.getLeftExpression()));
+        } catch (TranslatorException e) {
+            exceptions.add(e);
+        }
+    }
+
+    public void parseFunction( Function func ) {
+        String functionName = func.getName();
+        try {
+            if (functionName.equalsIgnoreCase("includes")) { //$NON-NLS-1$
+                generateMultiSelect(func, INCLUDES);
+            } else if (functionName.equalsIgnoreCase("excludes")) { //$NON-NLS-1$
+                generateMultiSelect(func, EXCLUDES);
+            }
+        } catch (TranslatorException e) {
+            exceptions.add(e);
+        }
+    }
+
+    private void generateMultiSelect( Function func,
+                                      String funcName ) throws TranslatorException {
+        List<Expression> expressions = func.getParameters();
+        validateFunction(expressions);
+        Expression columnExpression = expressions.get(0);
+        Column column = ((ColumnReference)columnExpression).getMetadataObject();
+        StringBuffer criterion = new StringBuffer();
+        criterion.append(column.getNameInSource()).append(SPACE).append(funcName);
+        addFunctionParams((Literal)expressions.get(1), criterion);
+        criteriaList.add(criterion.toString());
+    }
+
+    private void appendMultiselectIn( Column column,
+                                      In criteria ) throws TranslatorException {
+        StringBuffer result = new StringBuffer();
+        result.append(column.getNameInSource()).append(SPACE);
+        if (criteria.isNegated()) {
+            result.append(EXCLUDES).append(SPACE);
+        } else {
+            result.append(INCLUDES).append(SPACE);
+        }
+        result.append('(');
+        List<Expression> rightExpressions = criteria.getRightExpressions();
+        Iterator<Expression> iter = rightExpressions.iterator();
+        boolean first = true;
+        while (iter.hasNext()) {
+            Expression rightExpression = iter.next();
+            if (first) {
+                result.append(rightExpression.toString());
+                first = false;
+            } else {
+                result.append(COMMA).append(rightExpression.toString());
+            }
+
+        }
+        result.append(')');
+        criteriaList.add(result.toString());
+    }
+
+    private void validateFunction( List<Expression> expressions ) throws TranslatorException {
+        if (expressions.size() != 2) {
+            throw new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.invalid.arg.count")); //$NON-NLS-1$
+        }
+        if (!(expressions.get(0) instanceof ColumnReference)) {
+            throw new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.function.not.column.arg")); //$NON-NLS-1$
+        }
+        if (!(expressions.get(1) instanceof Literal)) {
+            throw new TranslatorException(SalesForcePlugin.Util.getString("CriteriaVisitor.function.not.literal.arg")); //$NON-NLS-1$
+        }
+    }
+
+    private void addFunctionParams( Literal param,
+                                    StringBuffer criterion ) {
+        criterion.append(OPEN);
+        boolean first = true;
+        String fullParam = param.toString();
+        String[] params = fullParam.split(","); //$NON-NLS-1$
+        for (int i = 0; i < params.length; i++) {
+            String token = params[i];
+            if (first) {
+                criterion.append(SPACE).append(Util.addSingleQuotes(token));
+                first = false;
+            } else {
+                criterion.append(COMMA).append(SPACE).append(Util.addSingleQuotes(token));
+            }
+        }
+        criterion.append(CLOSE);
+    }
+
+    protected void addCompareCriteria( List criteriaList,
+                                       Comparison compCriteria ) throws TranslatorException {
+        Expression lExpr = compCriteria.getLeftExpression();
+        if (lExpr instanceof Function) {
+            parseFunction((Function)lExpr);
+        } else {
+            ColumnReference left = (ColumnReference)lExpr;
+            Column column = left.getMetadataObject();
+            String columnName = column.getNameInSource();
+            StringBuffer queryString = new StringBuffer();
+            queryString.append(column.getParent().getNameInSource());
+            queryString.append('.');
+            queryString.append(columnName).append(SPACE);
+            queryString.append(comparisonOperators.get(compCriteria.getOperator()));
+            queryString.append(' ');
+            Expression rExp = compCriteria.getRightExpression();
+            if(rExp instanceof Literal) {
+            	Literal literal = (Literal)rExp;
+            	if (column.getJavaType().equals(Boolean.class)) {
+            		queryString.append(((Boolean)literal.getValue()).toString());
+            	} else if (column.getJavaType().equals(java.sql.Timestamp.class)) {
+            		Timestamp datetime = (java.sql.Timestamp)literal.getValue();
+            		String value = Util.getSalesforceDateTimeFormat().format(datetime);
+            		String zoneValue = Util.getTimeZoneOffsetFormat().format(datetime);
+            		queryString.append(value).append(zoneValue.subSequence(0, 3)).append(':').append(zoneValue.subSequence(3, 5));
+            	} else if (column.getJavaType().equals(java.sql.Time.class)) {
+            		String value = Util.getSalesforceDateTimeFormat().format((java.sql.Time)literal.getValue());
+            		queryString.append(value);
+            	} else if (column.getJavaType().equals(java.sql.Date.class)) {
+            		String value = Util.getSalesforceDateFormat().format((java.sql.Date)literal.getValue());
+            		queryString.append(value);
+            	} else {
+            		queryString.append(compCriteria.getRightExpression().toString());
+            	}
+            } else if(rExp instanceof ColumnReference) {
+            	ColumnReference right = (ColumnReference)lExpr;
+                column = left.getMetadataObject();
+                columnName = column.getNameInSource();
+                queryString.append(columnName);
+            }
+
+            criteriaList.add(queryString.toString());
+
+            if (columnName.equals("IsDeleted")) { //$NON-NLS-1$
+                Literal isDeletedLiteral = (Literal)compCriteria.getRightExpression();
+                Boolean isDeleted = (Boolean)isDeletedLiteral.getValue();
+                if (isDeleted) {
+                    this.queryAll = isDeleted;
+                }
+            }
+        }
+    }
+
+    private void appendCriteria( In criteria ) throws TranslatorException {
+        StringBuffer queryString = new StringBuffer();
+        Expression leftExp = criteria.getLeftExpression();
+        if(isIdColumn(leftExp)) {
+        	idInCriteria  = criteria;
+        }
+        queryString.append(getValue(leftExp));
+        queryString.append(' ');
+        if (criteria.isNegated()) {
+            queryString.append("NOT "); //$NON-NLS-1$
+        }
+        queryString.append("IN"); //$NON-NLS-1$
+        queryString.append('(');
+        Column column = ((ColumnReference)criteria.getLeftExpression()).getMetadataObject();
+        boolean timeColumn = isTimeColumn(column);
+        boolean first = true;
+        Iterator iter = criteria.getRightExpressions().iterator();
+        while (iter.hasNext()) {
+            if (!first) queryString.append(',');
+            if (!timeColumn) queryString.append('\'');
+            queryString.append(getValue((Expression)iter.next()));
+            if (!timeColumn) queryString.append('\'');
+            first = false;
+        }
+        queryString.append(')');
+        criteriaList.add(queryString.toString());
+    }
+
+    private boolean isTimeColumn( Column column ) throws TranslatorException {
+        boolean result = false;
+        if (column.getJavaType().equals(java.sql.Timestamp.class) || column.getJavaType().equals(java.sql.Time.class)
+            || column.getJavaType().equals(java.sql.Date.class)) {
+            result = true;
+        }
+        return result;
+    }
+
+    protected String getValue( Expression expr ) throws TranslatorException {
+        String result;
+        if (expr instanceof ColumnReference) {
+            ColumnReference element = (ColumnReference)expr;
+            Column element2 = element.getMetadataObject();
+            result = element2.getNameInSource();
+        } else if (expr instanceof Literal) {
+            Literal literal = (Literal)expr;
+            result = literal.getValue().toString();
+        } else {
+            throw new RuntimeException("unknown type in SalesforceQueryExecution.getValue(): " + expr.toString()); //$NON-NLS-1$
+        }
+        return result;
+    }
+
+    protected void loadColumnMetadata( NamedTable group ) throws TranslatorException {
+        table = group.getMetadataObject();
+        String supportsQuery = table.getProperties().get("Supports Query"); //$NON-NLS-1$
+        if (!Boolean.valueOf(supportsQuery)) {
+            throw new TranslatorException(table.getNameInSource() + " " + SalesForcePlugin.Util.getString("CriteriaVisitor.query.not.supported")); //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        List<Column> columnIds = table.getColumns();
+        for (Column element : columnIds) {
+            // influences queryAll behavior
+            if (element.getNameInSource().equals("IsDeleted")) { //$NON-NLS-1$
+                String isDeleted = element.getDefaultValue();
+                if (Boolean.parseBoolean(isDeleted)) {
+                    this.queryAll = true;
+                }
+            }
+        }
+    }
+
+    protected boolean isIdColumn( Expression expression ) throws TranslatorException {
+        boolean result = false;
+        if (expression instanceof ColumnReference) {
+            Column element = ((ColumnReference)expression).getMetadataObject();
+            String nameInSource = element.getNameInSource();
+            if (nameInSource.equalsIgnoreCase("id")) { //$NON-NLS-1$
+                result = true;
+            }
+        }
+        return result;
+    }
+
+    protected boolean isMultiSelectColumn( Expression expression ) throws TranslatorException {
+        boolean result = false;
+        if (expression instanceof ColumnReference) {
+            Column element = ((ColumnReference)expression).getMetadataObject();
+            String nativeType = element.getNativeType();
+            if (MULTIPICKLIST.equalsIgnoreCase(nativeType) || RESTRICTEDMULTISELECTPICKLIST.equalsIgnoreCase(nativeType)) {
+                result = true;
+            }
+        }
+        return result;
+    }
+
+    public boolean hasCriteria() {
+        return hasCriteria;
+    }
+
+    public void setHasCriteria( boolean hasCriteria,
+                                boolean isIdCriteria ) {
+        if (isIdCriteria) {
+            if (hasCriteria()) {
+                this.onlyIDCriteria = false;
+            } else {
+                this.onlyIDCriteria = true;
+            }
+        } else if (this.onlyIDCriteria) {
+            this.onlyIDCriteria = false;
+        }
+        this.hasCriteria = hasCriteria;
+    }
+
+    public boolean hasOnlyIDCriteria() {
+        return this.onlyIDCriteria;
+    }
+
+    public String getTableName() throws TranslatorException {
+        return table.getNameInSource();
+    }
+    
+    protected void addCriteriaString(StringBuffer result) {
+    	if(hasCriteria()) {
+			result.append(WHERE).append(SPACE);
+			for (String string : criteriaList) {
+				result.append(string);
+			}
+			result.append(SPACE);
+		}
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java
===================================================================
--- trunk/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,174 +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.visitors;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.language.Select;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-import org.teiid.metadata.Column.SearchType;
-import org.teiid.query.metadata.CompositeMetadataStore;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.RealMetadataFactory;
-import org.teiid.translator.salesforce.execution.visitors.JoinQueryVisitor;
-import org.teiid.translator.salesforce.execution.visitors.SelectVisitor;
-
-
-public class TestVisitors {
-
-    public static QueryMetadataInterface exampleSalesforce() { 
-    	MetadataStore store = new MetadataStore();
-        // Create models
-        Schema salesforceModel = RealMetadataFactory.createPhysicalModel("SalesforceModel", store); //$NON-NLS-1$
-       
-        // Create Account group
-        Table accounTable = RealMetadataFactory.createPhysicalGroup("Account", salesforceModel); //$NON-NLS-1$
-        accounTable.setNameInSource("Account"); //$NON-NLS-1$
-        accounTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
-        // Create Account Columns
-        String[] acctNames = new String[] {
-            "ID", "Name", "Stuff", "Industry"  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        };
-        String[] acctTypes = new String[] {  
-            DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
-        };
-        
-        List<Column> acctCols = RealMetadataFactory.createElements(accounTable, acctNames, acctTypes);
-        acctCols.get(2).setNativeType("multipicklist"); //$NON-NLS-1$
-        acctCols.get(2).setSearchType(SearchType.Like_Only);
-        // Set name in source on each column
-        String[] accountNameInSource = new String[] {
-           "id", "AccountName", "Stuff", "Industry"             //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$  
-        };
-        for(int i=0; i<2; i++) {
-            Column obj = acctCols.get(i);
-            obj.setNameInSource(accountNameInSource[i]);
-        }
-        
-        // Create Contact group
-        Table contactTable = RealMetadataFactory.createPhysicalGroup("Contacts", salesforceModel); //$NON-NLS-1$
-        contactTable.setNameInSource("Contact"); //$NON-NLS-1$
-        contactTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
-        // Create Contact Columns
-        String[] elemNames = new String[] {
-            "ContactID", "Name", "AccountId"  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        };
-        String[] elemTypes = new String[] {  
-            DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING 
-        };
-        
-        List<Column> contactCols = RealMetadataFactory.createElements(contactTable, elemNames, elemTypes);
-        // Set name in source on each column
-        String[] contactNameInSource = new String[] {
-           "id", "ContactName", "accountid"  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        };
-        for(int i=0; i<2; i++) {
-            Column obj = contactCols.get(i);
-            obj.setNameInSource(contactNameInSource[i]);
-        }
-        return new TransformationMetadata(null, new CompositeMetadataStore(store), null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
-    }    
-
-	private static TranslationUtility translationUtility = new TranslationUtility(exampleSalesforce());
-
-	@Test public void testOr() throws Exception {
-		Select command = (Select)translationUtility.parseCommand("select * from Account where Name = 'foo' or Stuff = 'bar'"); //$NON-NLS-1$
-		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
-		visitor.visit(command);
-		assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName = 'foo') OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-	}
-	
-	@Test public void testNot() throws Exception {
-		Select command = (Select)translationUtility.parseCommand("select * from Account where not (Name = 'foo' and Stuff = 'bar')"); //$NON-NLS-1$
-		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
-		visitor.visit(command);
-		assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName != 'foo') OR (Account.Stuff != 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-	}
-	
-	@Test public void testCountStart() throws Exception {
-		Select command = (Select)translationUtility.parseCommand("select count(*) from Account"); //$NON-NLS-1$
-		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
-		visitor.visit(command);
-		assertEquals("SELECT count() FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-	}
-	
-	@Test public void testNotLike() throws Exception {
-		Select command = (Select)translationUtility.parseCommand("select * from Account where Name not like '%foo' or Stuff = 'bar'"); //$NON-NLS-1$
-		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
-		visitor.visit(command);
-		assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (NOT (Account.AccountName LIKE '%foo')) OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-	}
-
-	
-	@Test public void testIN() throws Exception {
-		Select command = (Select)translationUtility.parseCommand("select * from Account where Industry IN (1,2,3)"); //$NON-NLS-1$
-		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
-		visitor.visit(command);
-		assertFalse(visitor.hasOnlyIDCriteria());
-		assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE Industry IN('1','2','3')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-		
-	}
-
-	@Test public void testOnlyIDsIN() throws Exception {
-		// this can resolve to a better performing retrieve call
-		Select command = (Select)translationUtility.parseCommand("select * from Account where ID IN (1,2,3)"); //$NON-NLS-1$
-		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
-		visitor.visit(command);
-		assertTrue(visitor.hasOnlyIdInCriteria());
-		assertEquals("Account", visitor.getTableName());
-		assertEquals("Account.id, Account.AccountName, Account.Stuff, Account.Industry", visitor.getRetrieveFieldList());
-		assertEquals(Arrays.asList(new String[]{"1", "2", "3"}), visitor.getIdInCriteria());	
-	}
-	
-	@Test public void testJoin() throws Exception {
-		Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contacts.Name FROM Contacts LEFT OUTER JOIN Account ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
-		SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
-		visitor.visit(command);
-		assertEquals("SELECT Account.AccountName, Contact.ContactName FROM Contact", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-	}
-	
-	@Test public void testJoin2() throws Exception {
-		Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contacts.Name FROM Account LEFT OUTER JOIN Contacts ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
-		SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
-		visitor.visit(command);
-		assertEquals("SELECT Account.AccountName, (SELECT Contact.ContactName FROM Contacts) FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-	}
-	
-	@Test public void testInWithNameInSourceDifferent() throws Exception {
-		Select command = (Select)translationUtility.parseCommand("SELECT Contacts.Name FROM Contacts WHERE Contacts.Name in ('x', 'y')"); //$NON-NLS-1$
-		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
-		visitor.visit(command);
-		assertEquals("SELECT Contact.ContactName FROM Contact WHERE ContactName IN('x','y')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-	}
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java (from rev 2802, trunk/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,199 @@
+/*
+ * 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.visitors;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.TimeZone;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.cdk.api.TranslationUtility;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.language.Select;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.Column.SearchType;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.salesforce.Constants;
+import org.teiid.translator.salesforce.SalesforceConnection;
+import org.teiid.translator.salesforce.execution.QueryExecutionImpl;
+
+ at SuppressWarnings("nls")
+public class TestVisitors {
+
+    public static QueryMetadataInterface exampleSalesforce() { 
+    	MetadataStore store = new MetadataStore();
+        // Create models
+        Schema salesforceModel = RealMetadataFactory.createPhysicalModel("SalesforceModel", store); //$NON-NLS-1$
+       
+        // Create Account group
+        Table accountTable = RealMetadataFactory.createPhysicalGroup("Account", salesforceModel); //$NON-NLS-1$
+        accountTable.setNameInSource("Account"); //$NON-NLS-1$
+        accountTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
+        accountTable.setProperty(Constants.SUPPORTS_RETRIEVE, Boolean.TRUE.toString());
+        // Create Account Columns
+        String[] acctNames = new String[] {
+            "ID", "Name", "Stuff", "Industry"  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+        };
+        String[] acctTypes = new String[] {  
+            DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
+        };
+        
+        List<Column> acctCols = RealMetadataFactory.createElements(accountTable, acctNames, acctTypes);
+        acctCols.get(2).setNativeType("multipicklist"); //$NON-NLS-1$
+        acctCols.get(2).setSearchType(SearchType.Like_Only);
+        // Set name in source on each column
+        String[] accountNameInSource = new String[] {
+           "id", "AccountName", "Stuff", "Industry"             //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$  
+        };
+        for(int i=0; i<2; i++) {
+            Column obj = acctCols.get(i);
+            obj.setNameInSource(accountNameInSource[i]);
+        }
+        
+        // Create Contact group
+        Table contactTable = RealMetadataFactory.createPhysicalGroup("Contacts", salesforceModel); //$NON-NLS-1$
+        contactTable.setNameInSource("Contact"); //$NON-NLS-1$
+        contactTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
+        // Create Contact Columns
+        String[] elemNames = new String[] {
+            "ContactID", "Name", "AccountId", "InitialContact"  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        };
+        String[] elemTypes = new String[] {  
+            DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.TIMESTAMP 
+        };
+        
+        List<Column> contactCols = RealMetadataFactory.createElements(contactTable, elemNames, elemTypes);
+        // Set name in source on each column
+        String[] contactNameInSource = new String[] {
+           "id", "ContactName", "accountid", "InitialContact"  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        };
+        for(int i=0; i<2; i++) {
+            Column obj = contactCols.get(i);
+            obj.setNameInSource(contactNameInSource[i]);
+        }
+        return new TransformationMetadata(null, new CompositeMetadataStore(store), null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
+    }    
+
+	private static TranslationUtility translationUtility = new TranslationUtility(exampleSalesforce());
+
+	@Test public void testOr() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("select * from Account where Name = 'foo' or Stuff = 'bar'"); //$NON-NLS-1$
+		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+		visitor.visit(command);
+		assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName = 'foo') OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+	}
+	
+	@Test public void testNot() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("select * from Account where not (Name = 'foo' and Stuff = 'bar')"); //$NON-NLS-1$
+		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+		visitor.visit(command);
+		assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName != 'foo') OR (Account.Stuff != 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+	}
+	
+	@Test public void testCountStart() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("select count(*) from Account"); //$NON-NLS-1$
+		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+		visitor.visit(command);
+		assertEquals("SELECT count() FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+	}
+	
+	@Test public void testNotLike() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("select * from Account where Name not like '%foo' or Stuff = 'bar'"); //$NON-NLS-1$
+		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+		visitor.visit(command);
+		assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (NOT (Account.AccountName LIKE '%foo')) OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+	}
+
+	
+	@Test public void testIN() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("select * from Account where Industry IN (1,2,3)"); //$NON-NLS-1$
+		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+		visitor.visit(command);
+		assertFalse(visitor.hasOnlyIDCriteria());
+		assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE Industry IN('1','2','3')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+		
+	}
+
+	@Test public void testOnlyIDsIN() throws Exception {
+		// this can resolve to a better performing retrieve call
+		Select command = (Select)translationUtility.parseCommand("select * from Account where ID IN (1,2,3)"); //$NON-NLS-1$
+		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+		visitor.visit(command);
+		assertTrue(visitor.hasOnlyIdInCriteria());
+		assertEquals("Account", visitor.getTableName());
+		assertEquals("Account.id, Account.AccountName, Account.Stuff, Account.Industry", visitor.getRetrieveFieldList());
+		assertEquals(Arrays.asList(new String[]{"1", "2", "3"}), visitor.getIdInCriteria());	
+	}
+	
+	@Test public void testJoin() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contacts.Name FROM Contacts LEFT OUTER JOIN Account ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
+		SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
+		visitor.visit(command);
+		assertEquals("SELECT Account.AccountName, Contact.ContactName FROM Contact", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+	}
+	
+	@Test public void testJoin2() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contacts.Name FROM Account LEFT OUTER JOIN Contacts ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
+		SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
+		visitor.visit(command);
+		assertEquals("SELECT Account.AccountName, (SELECT Contact.ContactName FROM Contacts) FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+	}
+	
+	@Test public void testInWithNameInSourceDifferent() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("SELECT Contacts.Name FROM Contacts WHERE Contacts.Name in ('x', 'y')"); //$NON-NLS-1$
+		SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+		visitor.visit(command);
+		assertEquals("SELECT Contact.ContactName FROM Contact WHERE ContactName IN('x','y')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+	}
+	
+	@Test public void testIDCriteria() throws Exception {
+		Select command = (Select)translationUtility.parseCommand("select id, name from Account where id = 'bar'"); //$NON-NLS-1$
+		SalesforceConnection sfc = Mockito.mock(SalesforceConnection.class);
+		QueryExecutionImpl qei = new QueryExecutionImpl(command, sfc, translationUtility.createRuntimeMetadata(), Mockito.mock(ExecutionContext.class));
+		qei.execute();
+		Mockito.verify(sfc).retrieve("Account.id, Account.AccountName", "Account", Arrays.asList("bar"));
+	}
+	
+	@Test public void testDateTimeFormating() throws Exception {
+		TimeZone.setDefault(TimeZone.getTimeZone("GMT-06:00"));
+		try {
+			Select command = (Select)translationUtility.parseCommand("select name from contacts where initialcontact = {ts'2003-03-11 11:42:10.5'}"); //$NON-NLS-1$
+			SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+			visitor.visit(command);
+			assertEquals("SELECT Contact.ContactName FROM Contact WHERE Contact.InitialContact = 2003-03-11T11:42:10.500-06:00", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+		} finally {
+			TimeZone.setDefault(null);
+		}
+	}
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ws/pom.xml
===================================================================
--- trunk/connectors/translator-ws/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ws/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/connectors/translator-ws/pom.xml (from rev 2804, trunk/connectors/translator-ws/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ws/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/connectors/translator-ws/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/console/pom.xml
===================================================================
--- trunk/console/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/console/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,175 +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.3.0.Alpha2-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>
-		<teiid.version>${project.version}</teiid.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>
-		</resources>
-	</build>
-
-
-</project>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha2/console/pom.xml (from rev 2804, trunk/console/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/console/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/console/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,175 @@
+<?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.3.0.Alpha2</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>
+		<teiid.version>${project.version}</teiid.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>
+		</resources>
+	</build>
+
+
+</project>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha2/documentation/admin-guide/pom.xml
===================================================================
--- trunk/documentation/admin-guide/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/admin-guide/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/documentation/admin-guide/pom.xml (from rev 2804, trunk/documentation/admin-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/documentation/admin-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/admin-guide/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/documentation/caching-guide/pom.xml
===================================================================
--- trunk/documentation/caching-guide/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/caching-guide/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/documentation/caching-guide/pom.xml (from rev 2804, trunk/documentation/caching-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/documentation/caching-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/caching-guide/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/documentation/client-developers-guide/pom.xml
===================================================================
--- trunk/documentation/client-developers-guide/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/client-developers-guide/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/documentation/client-developers-guide/pom.xml (from rev 2804, trunk/documentation/client-developers-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/documentation/client-developers-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/client-developers-guide/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/documentation/developer-guide/pom.xml
===================================================================
--- trunk/documentation/developer-guide/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/developer-guide/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/documentation/developer-guide/pom.xml (from rev 2804, trunk/documentation/developer-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/documentation/developer-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/developer-guide/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/documentation/pom.xml
===================================================================
--- trunk/documentation/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/documentation/pom.xml (from rev 2804, trunk/documentation/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/documentation/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/documentation/quick-start-example/pom.xml
===================================================================
--- trunk/documentation/quick-start-example/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/quick-start-example/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/documentation/quick-start-example/pom.xml (from rev 2804, trunk/documentation/quick-start-example/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/documentation/quick-start-example/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/quick-start-example/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/documentation/reference/pom.xml
===================================================================
--- trunk/documentation/reference/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/reference/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/documentation/reference/pom.xml (from rev 2804, trunk/documentation/reference/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/documentation/reference/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/reference/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/documentation/reference/src/main/docbook/en-US/content/system_schema.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/system_schema.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/reference/src/main/docbook/en-US/content/system_schema.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,1810 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
-<chapter id="system_schema">
-    <title>System Schema</title>
-    <para>The built-in SYS and SYSADMIN schemas provide metadata tables and procedures against the current VDB.</para>
-	<section id="system_tables">
-		<title>System Tables</title>
-		<section>
-			<title>VDB, Schema, and Properties</title>
-			<section>
-				<title>SYSADMIN.VDBResources</title>
-				<para>This table provides the current VDB contents.</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>resourcePath</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>The path to the contents.</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>contents</para>
-								</entry>
-								<entry>
-									<para>blob</para>
-								</entry>
-								<entry>
-									<para>The contents as a blob.</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-			<section>
-				<title>SYS.VirtualDatabases</title>
-				<para>This table supplies information about the currently
-					connected
-					virtual database, of which there is always exactly one
-					(in the
-					context of a connection).</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>The name of the VDB</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Version</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>The version of the VDB</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-			<section>
-				<title>SYS.Schemas</title>
-				<para>This table supplies information about all the schemas in
-					the
-					virtual database, including the system schema itself
-					(System).
-				</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>VDBName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>VDB name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Schema name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsPhysical</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>True if this represents a source</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>UID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Unique ID</para>
-								</entry>
-							</row>
-                            <row>
-                                <entry>
-                                    <para>OID</para>
-                                </entry>
-                                <entry>
-                                    <para>integer</para>
-                                </entry>
-                                <entry>
-                                    <para>Unique ID</para>
-                                </entry>
-                            </row>                            
-							<row>
-								<entry>
-									<para>Description</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>PrimaryMetamodelURI</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>URI for the primary metamodel describing the model used
-										for this schema</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-			<section>
-				<title>SYS.Properties</title>
-				<para>This table supplies user-defined properties on all objects
-					based on metamodel extensions. Normally, this table is empty if
-					no
-					metamodel extensions are being used.</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Extension property name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Value</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Extension property value</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>UID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Key unique ID</para>
-								</entry>
-							</row>
-                            <row>
-                                <entry>
-                                    <para>OID</para>
-                                </entry>
-                                <entry>
-                                    <para>integer</para>
-                                </entry>
-                                <entry>
-                                    <para>Unique ID</para>
-                                </entry>
-                            </row>                             
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-		</section>
-		<section>
-			<title>Table Metadata</title>
-			<section>
-				<title>SYS.Tables</title>
-				<para>This table supplies information about all the groups
-					(tables,
-					views, documents, etc) in the virtual database.</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>VDBName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>VDB name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SchemaName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Schema Name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Short group name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Table type (Table, View, Document, ...)
-                </para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>NameInSource</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Name of this group in the source</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsPhysical</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>True if this is a source table</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SupportsUpdates</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>True if group can be updated</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>UID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Group unique ID</para>
-								</entry>
-							</row>
-                            <row>
-                                <entry>
-                                    <para>OID</para>
-                                </entry>
-                                <entry>
-                                    <para>integer</para>
-                                </entry>
-                                <entry>
-                                    <para>Unique ID</para>
-                                </entry>
-                            </row>                             
-							<row>
-								<entry>
-									<para>Cardinality</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Approximate number of rows in the group
-                </para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Description</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsSystem</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>True if in system table</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-			<section>
-				<title>SYSADMIN.MatViews</title>
-				<para>This table supplies information about all the materailized views in the virtual database.</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>VDBName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>VDB name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SchemaName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Schema Name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Short group name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>TargetSchemaName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Name of the materialized table schema</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>TargetName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Name of the materialized table</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Valid</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>True if materialized table is currently valid.</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>LoadState</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>The load state, can be one of NEEDS_LOADING, LOADING, LOADED, FAILED_LOAD</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Updated</para>
-								</entry>
-								<entry>
-									<para>timestamp</para>
-								</entry>
-								<entry>
-									<para>The timestamp of the last full refresh.</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Cardinality</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>The number of rows in the materialized view table.</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-			<section>
-				<title>SYS.Columns</title>
-				<para>This table supplies information about all the elements
-					(columns, tags, attributes, etc) in the virtual database.</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>VDBName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>VDB name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SchemaName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Schema Name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>TableName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Table name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Element name (not qualified)</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Position</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Position in group (1-based)</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>NameInSource</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Name of element in source</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>DataType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Teiid runtime data type name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Scale</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Number of digits after the decimal point
-                </para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>ElementLength</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Element length (mostly used for strings)
-                </para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>sLengthFixed</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Whether the length is fixed or variable
-                </para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SupportsSelect</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Element can be used in SELECT</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SupportsUpdates</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Values can be inserted or updated in the
-										element</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsCaseSensitive</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Element is case-sensitive</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsSigned</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Element is signed numeric value</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsCurrency</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Element represents monetary value</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsAutoIncremented</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Element is auto-incremented in the source
-                </para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>NullType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Nullability: "Nullable", "No Nulls",
-										"Unknown"</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>MinRange</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Minimum numeric value</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>MaxRange</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Maximum numeric value</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SearchType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Searchability: "Searchable", "All
-										Except Like", "Like
-										Only", "Unsearchable"</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Format</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Format of string value</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>DefaultValue</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Default value</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>JavaClass</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Java class that will be returned</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Precision</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Number of digits in numeric value</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>CharOctetLength</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Measure of return value size</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Radix</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Radix for numeric values</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>GroupUpperName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Upper-case full group name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>UpperName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Upper-case element name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>UID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Element unique ID</para>
-								</entry>
-							</row>
-                            <row>
-                                <entry>
-                                    <para>OID</para>
-                                </entry>
-                                <entry>
-                                    <para>integer</para>
-                                </entry>
-                                <entry>
-                                    <para>Unique ID</para>
-                                </entry>
-                            </row>                             
-							<row>
-								<entry>
-									<para>Description</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-			<section>
-				<title>SYS.Keys</title>
-				<para>This table supplies information about primary, foreign,
-					and
-					unique keys.</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>VDBName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>VDB name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SchemaName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Schema Name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Table Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Table name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Key name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Description</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>NameInSource</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Name of key in source system</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Type of key: "Primary", "Foreign", "Unique",
-										etc</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsIndexed</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>True if key is indexed</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>RefKeyUID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Referenced key UID (if foreign key)
-                </para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>UID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Key unique ID</para>
-								</entry>
-							</row>
-                            <row>
-                                <entry>
-                                    <para>OID</para>
-                                </entry>
-                                <entry>
-                                    <para>integer</para>
-                                </entry>
-                                <entry>
-                                    <para>Unique ID</para>
-                                </entry>
-                            </row>                             
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-			<section>
-				<title>SYS.KeyColumns</title>
-				<para>This table supplies information about the columns
-					referenced by
-					a key.</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>VDBName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>VDB name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SchemaName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Schema Name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>TableName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Table name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Element name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>KeyName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Key name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>KeyType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Key type: "Primary", "Foreign", "Unique", etc
-                </para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>RefKeyUID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Referenced key UID</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>UID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Key UID</para>
-								</entry>
-							</row>
-                            <row>
-                                <entry>
-                                    <para>OID</para>
-                                </entry>
-                                <entry>
-                                    <para>integer</para>
-                                </entry>
-                                <entry>
-                                    <para>Unique ID</para>
-                                </entry>
-                            </row>                             
-							<row>
-								<entry>
-									<para>Position</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Position in key</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-		</section>
-		<section>
-			<title>
-				Procedure Metadata
-    </title>
-			<section>
-				<title>SYS.Procedures</title>
-				<para>This table supplies information about the procedures in
-					the
-					virtual database.</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>VDBName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>VDB name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SchemaName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Schema Name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Procedure name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>NameInSource</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Procedure name in source system</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>ReturnsResults</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Returns a result set</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>UID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Procedure UID</para>
-								</entry>
-							</row>
-                            <row>
-                                <entry>
-                                    <para>OID</para>
-                                </entry>
-                                <entry>
-                                    <para>integer</para>
-                                </entry>
-                                <entry>
-                                    <para>Unique ID</para>
-                                </entry>
-                            </row>                             
-							<row>
-								<entry>
-									<para>Description</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-			<section>
-				<title>SYS.ProcedureParams</title>
-				<para>This supplies information on procedure parameters.
-      </para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>VDBName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>VDB name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SchemaName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Schema Name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>ProcedureName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Procedure name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Parameter name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>DataType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Teiid runtime data type name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Position</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Position in procedure args</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Parameter direction: "In", "Out",
-										"InOut", "ResultSet",
-										"ReturnValue"</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Optional</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Parameter is optional</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Precision</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Precision of parameter</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>TypeLength</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Length of parameter value</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Scale</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Scale of parameter</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Radix</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Radix of parameter</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>NullType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Nullability: "Nullable", "No Nulls",
-										"Unknown"</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-		</section>
-		<section>
-			<title>
-				Datatype Metadata
-    </title>
-			<section>
-				<title>SYS.DataTypes</title>
-				<para>
-					This table supplies information on
-					<link linkend="datatypes">datatypes</link>
-					.
-				</para>
-				<informaltable frame="all">
-					<tgroup cols="3">
-						<thead>
-							<row>
-								<entry>
-									<para>Column Name</para>
-								</entry>
-								<entry>
-									<para>Type</para>
-								</entry>
-								<entry>
-									<para>Description</para>
-								</entry>
-							</row>
-						</thead>
-						<tbody>
-							<row>
-								<entry>
-									<para>Name</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Teiid design-time type name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsStandard</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Always false</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsPhysical</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Always false</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>TypeName</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Design-time type name (same as Name)
-                </para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>JavaClass</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Java class returned for this type</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Scale</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Max scale of this type</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>TypeLength</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Max length of this type</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>NullType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Nullability: "Nullable", "No Nulls",
-										"Unknown"</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsSigned</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Is signed numeric?</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsAutoIncremented</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Is auto-incremented?</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>IsCaseSensitive</para>
-								</entry>
-								<entry>
-									<para>boolean</para>
-								</entry>
-								<entry>
-									<para>Is case-sensitive?</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Precision</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Max precision of this type</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Radix</para>
-								</entry>
-								<entry>
-									<para>integer</para>
-								</entry>
-								<entry>
-									<para>Radix of this type</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>SearchType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Searchability: "Searchable", "All
-										Except Like", "Like
-										Only", "Unsearchable"</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>UID</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Data type unique ID</para>
-								</entry>
-							</row>
-                            <row>
-                                <entry>
-                                    <para>OID</para>
-                                </entry>
-                                <entry>
-                                    <para>integer</para>
-                                </entry>
-                                <entry>
-                                    <para>Unique ID</para>
-                                </entry>
-                            </row>                             
-							<row>
-								<entry>
-									<para>RuntimeType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Teiid runtime data type name</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>BaseType</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Base type</para>
-								</entry>
-							</row>
-							<row>
-								<entry>
-									<para>Description</para>
-								</entry>
-								<entry>
-									<para>string</para>
-								</entry>
-								<entry>
-									<para>Description of type</para>
-								</entry>
-							</row>
-						</tbody>
-					</tgroup>
-				</informaltable>
-			</section>
-		</section>
-	</section>
-	<section id="system_procedures">
-		<title>System Procedures</title>
-		<informaltable frame="all">
-			<tgroup cols="3">
-				<thead>
-					<row>
-						<entry>
-							<para>Procedure</para>
-						</entry>
-						<entry>
-							<para>Parameters</para>
-						</entry>
-						<entry>
-							<para>ResultSet</para>
-						</entry>
-					</row>
-				</thead>
-				<tbody>
-					<row>
-						<entry>
-							<para>SYS.getXMLSchemas</para>
-						</entry>
-						<entry>
-							<para>(string document)</para>
-						</entry>
-						<entry>
-							<para>A single column containing the schemas as clobs.</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>SYSADMIN.refreshMatView</para>
-						</entry>
-						<entry>
-							<para>(string ViewName, boolean Invalidate)</para>
-						</entry>
-						<entry>
-							<para>An return return value, RowsUpdated. -1 indicates a load is in progress, otherwise the cardinality of the table is returned.  See the Caching Guide for more.</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>SYSADMIN.refreshMatViewRow</para>
-						</entry>
-						<entry>
-							<para>(string ViewName, object Key)</para>
-						</entry>
-						<entry>
-							<para>An return return value, RowsUpdated. -1 indicates the materialized table is currently invalid. 0 indicates that the specified row did not exist in the live data query or in the materialized table.  See the Caching Guide for more.</para>
-						</entry>
-					</row>
-				</tbody>
-			</tgroup>
-		</informaltable>
-	</section>
-</chapter>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha2/documentation/reference/src/main/docbook/en-US/content/system_schema.xml (from rev 2802, trunk/documentation/reference/src/main/docbook/en-US/content/system_schema.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/documentation/reference/src/main/docbook/en-US/content/system_schema.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/documentation/reference/src/main/docbook/en-US/content/system_schema.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,1816 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
+<chapter id="system_schema">
+    <title>System Schema</title>
+    <para>The built-in SYS and SYSADMIN schemas provide metadata tables and procedures against the current VDB.</para>
+	<section id="system_tables">
+		<title>System Tables</title>
+		<section>
+			<title>VDB, Schema, and Properties</title>
+			<section>
+				<title>SYSADMIN.VDBResources</title>
+				<para>This table provides the current VDB contents.</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>resourcePath</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>The path to the contents.</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>contents</para>
+								</entry>
+								<entry>
+									<para>blob</para>
+								</entry>
+								<entry>
+									<para>The contents as a blob.</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+			<section>
+				<title>SYS.VirtualDatabases</title>
+				<para>This table supplies information about the currently
+					connected
+					virtual database, of which there is always exactly one
+					(in the
+					context of a connection).</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>The name of the VDB</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Version</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>The version of the VDB</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+			<section>
+				<title>SYS.Schemas</title>
+				<para>This table supplies information about all the schemas in
+					the
+					virtual database, including the system schema itself
+					(System).
+				</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>VDBName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>VDB name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Schema name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsPhysical</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>True if this represents a source</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>UID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Unique ID</para>
+								</entry>
+							</row>
+                            <row>
+                                <entry>
+                                    <para>OID</para>
+                                </entry>
+                                <entry>
+                                    <para>integer</para>
+                                </entry>
+                                <entry>
+                                    <para>Unique ID (see note below)</para>
+                                </entry>
+                            </row>                            
+							<row>
+								<entry>
+									<para>Description</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>PrimaryMetamodelURI</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>URI for the primary metamodel describing the model used
+										for this schema</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+			<section>
+				<title>SYS.Properties</title>
+				<para>This table supplies user-defined properties on all objects
+					based on metamodel extensions. Normally, this table is empty if
+					no
+					metamodel extensions are being used.</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Extension property name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Value</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Extension property value</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>UID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Key unique ID</para>
+								</entry>
+							</row>
+                            <row>
+                                <entry>
+                                    <para>OID</para>
+                                </entry>
+                                <entry>
+                                    <para>integer</para>
+                                </entry>
+                                <entry>
+                                    <para>Unique ID (see note below)</para>
+                                </entry>
+                            </row>                             
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+		</section>
+		<section>
+			<title>Table Metadata</title>
+			<section>
+				<title>SYS.Tables</title>
+				<para>This table supplies information about all the groups
+					(tables,
+					views, documents, etc) in the virtual database.</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>VDBName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>VDB name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SchemaName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Schema Name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Short group name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Table type (Table, View, Document, ...)
+                </para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>NameInSource</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Name of this group in the source</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsPhysical</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>True if this is a source table</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SupportsUpdates</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>True if group can be updated</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>UID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Group unique ID</para>
+								</entry>
+							</row>
+                            <row>
+                                <entry>
+                                    <para>OID</para>
+                                </entry>
+                                <entry>
+                                    <para>integer</para>
+                                </entry>
+                                <entry>
+                                    <para>Unique ID (see note below)</para>
+                                </entry>
+                            </row>                             
+							<row>
+								<entry>
+									<para>Cardinality</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Approximate number of rows in the group
+                </para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Description</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsSystem</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>True if in system table</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+			<section>
+				<title>SYSADMIN.MatViews</title>
+				<para>This table supplies information about all the materailized views in the virtual database.</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>VDBName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>VDB name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SchemaName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Schema Name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Short group name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>TargetSchemaName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Name of the materialized table schema</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>TargetName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Name of the materialized table</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Valid</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>True if materialized table is currently valid.</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>LoadState</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>The load state, can be one of NEEDS_LOADING, LOADING, LOADED, FAILED_LOAD</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Updated</para>
+								</entry>
+								<entry>
+									<para>timestamp</para>
+								</entry>
+								<entry>
+									<para>The timestamp of the last full refresh.</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Cardinality</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>The number of rows in the materialized view table.</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+			<section>
+				<title>SYS.Columns</title>
+				<para>This table supplies information about all the elements
+					(columns, tags, attributes, etc) in the virtual database.</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>VDBName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>VDB name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SchemaName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Schema Name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>TableName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Table name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Element name (not qualified)</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Position</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Position in group (1-based)</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>NameInSource</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Name of element in source</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>DataType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Teiid runtime data type name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Scale</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Number of digits after the decimal point
+                </para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>ElementLength</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Element length (mostly used for strings)
+                </para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>sLengthFixed</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Whether the length is fixed or variable
+                </para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SupportsSelect</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Element can be used in SELECT</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SupportsUpdates</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Values can be inserted or updated in the
+										element</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsCaseSensitive</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Element is case-sensitive</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsSigned</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Element is signed numeric value</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsCurrency</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Element represents monetary value</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsAutoIncremented</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Element is auto-incremented in the source
+                </para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>NullType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Nullability: "Nullable", "No Nulls",
+										"Unknown"</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>MinRange</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Minimum numeric value</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>MaxRange</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Maximum numeric value</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SearchType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Searchability: "Searchable", "All
+										Except Like", "Like
+										Only", "Unsearchable"</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Format</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Format of string value</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>DefaultValue</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Default value</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>JavaClass</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Java class that will be returned</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Precision</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Number of digits in numeric value</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>CharOctetLength</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Measure of return value size</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Radix</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Radix for numeric values</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>GroupUpperName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Upper-case full group name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>UpperName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Upper-case element name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>UID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Element unique ID</para>
+								</entry>
+							</row>
+                            <row>
+                                <entry>
+                                    <para>OID</para>
+                                </entry>
+                                <entry>
+                                    <para>integer</para>
+                                </entry>
+                                <entry>
+                                    <para>Unique ID (see note below)</para>
+                                </entry>
+                            </row>                             
+							<row>
+								<entry>
+									<para>Description</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+			<section>
+				<title>SYS.Keys</title>
+				<para>This table supplies information about primary, foreign,
+					and
+					unique keys.</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>VDBName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>VDB name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SchemaName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Schema Name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Table Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Table name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Key name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Description</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>NameInSource</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Name of key in source system</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Type of key: "Primary", "Foreign", "Unique",
+										etc</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsIndexed</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>True if key is indexed</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>RefKeyUID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Referenced key UID (if foreign key)
+                </para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>UID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Key unique ID</para>
+								</entry>
+							</row>
+                            <row>
+                                <entry>
+                                    <para>OID</para>
+                                </entry>
+                                <entry>
+                                    <para>integer</para>
+                                </entry>
+                                <entry>
+                                    <para>Unique ID (see note below)</para>
+                                </entry>
+                            </row>                             
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+			<section>
+				<title>SYS.KeyColumns</title>
+				<para>This table supplies information about the columns
+					referenced by
+					a key.</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>VDBName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>VDB name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SchemaName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Schema Name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>TableName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Table name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Element name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>KeyName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Key name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>KeyType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Key type: "Primary", "Foreign", "Unique", etc
+                </para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>RefKeyUID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Referenced key UID</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>UID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Key UID</para>
+								</entry>
+							</row>
+                            <row>
+                                <entry>
+                                    <para>OID</para>
+                                </entry>
+                                <entry>
+                                    <para>integer</para>
+                                </entry>
+                                <entry>
+                                    <para>Unique ID (see note below)</para>
+                                </entry>
+                            </row>                             
+							<row>
+								<entry>
+									<para>Position</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Position in key</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+		</section>
+		<section>
+			<title>
+				Procedure Metadata
+    </title>
+			<section>
+				<title>SYS.Procedures</title>
+				<para>This table supplies information about the procedures in
+					the
+					virtual database.</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>VDBName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>VDB name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SchemaName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Schema Name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Procedure name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>NameInSource</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Procedure name in source system</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>ReturnsResults</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Returns a result set</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>UID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Procedure UID</para>
+								</entry>
+							</row>
+                            <row>
+                                <entry>
+                                    <para>OID</para>
+                                </entry>
+                                <entry>
+                                    <para>integer</para>
+                                </entry>
+                                <entry>
+                                    <para>Unique ID (see note below)</para>
+                                </entry>
+                            </row>                             
+							<row>
+								<entry>
+									<para>Description</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+			<section>
+				<title>SYS.ProcedureParams</title>
+				<para>This supplies information on procedure parameters.
+      </para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>VDBName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>VDB name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SchemaName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Schema Name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>ProcedureName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Procedure name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Parameter name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>DataType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Teiid runtime data type name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Position</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Position in procedure args</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Parameter direction: "In", "Out",
+										"InOut", "ResultSet",
+										"ReturnValue"</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Optional</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Parameter is optional</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Precision</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Precision of parameter</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>TypeLength</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Length of parameter value</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Scale</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Scale of parameter</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Radix</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Radix of parameter</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>NullType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Nullability: "Nullable", "No Nulls",
+										"Unknown"</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+		</section>
+		<section>
+			<title>
+				Datatype Metadata
+    </title>
+			<section>
+				<title>SYS.DataTypes</title>
+				<para>
+					This table supplies information on
+					<link linkend="datatypes">datatypes</link>
+					.
+				</para>
+				<informaltable frame="all">
+					<tgroup cols="3">
+						<thead>
+							<row>
+								<entry>
+									<para>Column Name</para>
+								</entry>
+								<entry>
+									<para>Type</para>
+								</entry>
+								<entry>
+									<para>Description</para>
+								</entry>
+							</row>
+						</thead>
+						<tbody>
+							<row>
+								<entry>
+									<para>Name</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Teiid design-time type name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsStandard</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Always false</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsPhysical</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Always false</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>TypeName</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Design-time type name (same as Name)
+                </para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>JavaClass</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Java class returned for this type</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Scale</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Max scale of this type</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>TypeLength</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Max length of this type</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>NullType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Nullability: "Nullable", "No Nulls",
+										"Unknown"</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsSigned</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Is signed numeric?</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsAutoIncremented</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Is auto-incremented?</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>IsCaseSensitive</para>
+								</entry>
+								<entry>
+									<para>boolean</para>
+								</entry>
+								<entry>
+									<para>Is case-sensitive?</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Precision</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Max precision of this type</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Radix</para>
+								</entry>
+								<entry>
+									<para>integer</para>
+								</entry>
+								<entry>
+									<para>Radix of this type</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>SearchType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Searchability: "Searchable", "All
+										Except Like", "Like
+										Only", "Unsearchable"</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>UID</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Data type unique ID</para>
+								</entry>
+							</row>
+                            <row>
+                                <entry>
+                                    <para>OID</para>
+                                </entry>
+                                <entry>
+                                    <para>integer</para>
+                                </entry>
+                                <entry>
+                                    <para>Unique ID (see note below)</para>
+                                </entry>
+                            </row>                             
+							<row>
+								<entry>
+									<para>RuntimeType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Teiid runtime data type name</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>BaseType</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Base type</para>
+								</entry>
+							</row>
+							<row>
+								<entry>
+									<para>Description</para>
+								</entry>
+								<entry>
+									<para>string</para>
+								</entry>
+								<entry>
+									<para>Description of type</para>
+								</entry>
+							</row>
+						</tbody>
+					</tgroup>
+				</informaltable>
+			</section>
+		</section>
+        <warning>
+		  <para>OID column is is guranteed to be unique only for given version of the VDB. If the VDB is updated and a different version of
+          the VDB is deployed, these IDs are not guranteed to be unique across both versions of VDB. UID is unique across different versions
+          only if the VDB is generated from Designer and metadata from old models are used(i.e. no re-importing from sources). 
+          UID column in a Dynamic VDB behaves same as OID column.</para>
+	  </warning>
+	</section>
+	<section id="system_procedures">
+		<title>System Procedures</title>
+		<informaltable frame="all">
+			<tgroup cols="3">
+				<thead>
+					<row>
+						<entry>
+							<para>Procedure</para>
+						</entry>
+						<entry>
+							<para>Parameters</para>
+						</entry>
+						<entry>
+							<para>ResultSet</para>
+						</entry>
+					</row>
+				</thead>
+				<tbody>
+					<row>
+						<entry>
+							<para>SYS.getXMLSchemas</para>
+						</entry>
+						<entry>
+							<para>(string document)</para>
+						</entry>
+						<entry>
+							<para>A single column containing the schemas as clobs.</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>SYSADMIN.refreshMatView</para>
+						</entry>
+						<entry>
+							<para>(string ViewName, boolean Invalidate)</para>
+						</entry>
+						<entry>
+							<para>An return return value, RowsUpdated. -1 indicates a load is in progress, otherwise the cardinality of the table is returned.  See the Caching Guide for more.</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>SYSADMIN.refreshMatViewRow</para>
+						</entry>
+						<entry>
+							<para>(string ViewName, object Key)</para>
+						</entry>
+						<entry>
+							<para>An return return value, RowsUpdated. -1 indicates the materialized table is currently invalid. 0 indicates that the specified row did not exist in the live data query or in the materialized table.  See the Caching Guide for more.</para>
+						</entry>
+					</row>
+				</tbody>
+			</tgroup>
+		</informaltable>
+	</section>
+</chapter>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/pom.xml
===================================================================
--- trunk/engine/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/engine/pom.xml (from rev 2804, trunk/engine/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/LobManager.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/common/buffer/LobManager.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/LobManager.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,223 +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.common.buffer;
-
-import java.io.BufferedOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-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.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.BlobImpl;
-import org.teiid.core.types.BlobType;
-import org.teiid.core.types.ClobImpl;
-import org.teiid.core.types.ClobType;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.InputStreamFactory;
-import org.teiid.core.types.SQLXMLImpl;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.types.XMLType;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.processor.xml.XMLUtil.FileStoreInputStreamFactory;
-import org.teiid.query.sql.symbol.Expression;
-
-/**
- * Tracks lob references so they are not lost during serialization.
- * TODO: for temp tables we may need to have a copy by value management strategy
- */
-public class LobManager {
-	private static final int IO_BUFFER_SIZE = 1 << 14;
-	private Map<String, Streamable<?>> lobReferences = new ConcurrentHashMap<String, Streamable<?>>();
-	private Map<String, Streamable<?>> lobFilestores = new ConcurrentHashMap<String, Streamable<?>>();
-
-	public void updateReferences(int[] lobIndexes, List<?> tuple)
-			throws TeiidComponentException {
-		for (int i = 0; i < lobIndexes.length; i++) {
-			Object anObj = tuple.get(lobIndexes[i]);
-			if (!(anObj instanceof Streamable<?>)) {
-				continue;
-			}
-			Streamable lob = (Streamable) anObj;
-			if (lob.getReference() == null) {
-				lob.setReference(getLobReference(lob.getReferenceStreamId()).getReference());
-			} else {
-				String id = lob.getReferenceStreamId();
-				this.lobReferences.put(id, lob);
-			}
-		}
-	}
-	
-    public Streamable<?> getLobReference(String id) throws TeiidComponentException {
-    	Streamable<?> lob = null;
-    	if (this.lobReferences != null) {
-    		lob = this.lobReferences.get(id);
-    	}
-    	
-    	if (lob == null) {
-			lob = this.lobFilestores.get(id);
-    	}
-    	
-    	if (lob == null) {
-    		throw new TeiidComponentException(QueryPlugin.Util.getString("ProcessWorker.wrongdata")); //$NON-NLS-1$
-    	}
-    	return lob;
-    }
-        
-    public void clear() {
-    	this.lobReferences.clear();
-    	this.lobFilestores.clear();
-    }
-    
-    public static int[] getLobIndexes(List expressions) {
-    	if (expressions == null) {
-    		return null;
-    	}
-		int[] result = new int[expressions.size()];
-		int resultIndex = 0;
-	    for (int i = 0; i < expressions.size(); i++) {
-	    	Expression expr = (Expression) expressions.get(i);
-	        if (DataTypeManager.isLOB(expr.getType()) || expr.getType() == DataTypeManager.DefaultDataClasses.OBJECT) {
-	        	result[resultIndex++] = i;
-	        }
-	    }
-	    if (resultIndex == 0) {
-	    	return null;
-	    }
-	    return Arrays.copyOf(result, resultIndex);
-    }
-
-    public Collection<Streamable<?>> getLobReferences(){
-    	return lobReferences.values();
-    }
-    
-	public void persist(FileStore lobStore) throws TeiidComponentException {
-		ArrayList<Streamable<?>> lobs = new ArrayList<Streamable<?>>(this.lobReferences.values());
-		for (Streamable<?> lob:lobs) {
-			persist(lob.getReferenceStreamId(), lobStore);
-		}
-	}    
-    
-	public Streamable<?> persist(String id, FileStore fs) throws TeiidComponentException {
-		Streamable<?> persistedLob = this.lobFilestores.get(id);
-		if (persistedLob == null) {
-			Streamable<?> lobReference =  this.lobReferences.get(id);
-			if (lobReference == null) {
-	    		throw new TeiidComponentException(QueryPlugin.Util.getString("ProcessWorker.wrongdata")); //$NON-NLS-1$
-	    	}
-	    	
-	    	persistedLob = persistLob(lobReference, fs);
-			synchronized (this) {
-				this.lobFilestores.put(id, persistedLob);
-				this.lobReferences.remove(id);		
-			}
-		}
-		return persistedLob;
-	}
-	
-	private Streamable<?> persistLob(final Streamable<?> lob, final FileStore store) throws TeiidComponentException {
-		long offset = store.getLength();
-		int length = 0;
-		Streamable<?> persistedLob;
-		
-		// if this is XML and already saved to disk just return
-		if (lob.getReference() instanceof SQLXMLImpl) {
-			try {
-				SQLXMLImpl xml = (SQLXMLImpl)lob.getReference();
-				InputStreamFactory isf = xml.getStreamFactory();
-				if (isf instanceof FileStoreInputStreamFactory) {
-					return lob;
-				}
-			} catch (SQLException e) {
-				// go through regular persistence.
-			}
-		}
-					
-		// stream the contents of lob into file store.
-		byte[] bytes = new byte[102400]; // 100k
-		try {
-			InputStreamFactory isf = new InputStreamFactory() {
-				@Override
-				public InputStream getInputStream() throws IOException {
-			    	if (lob instanceof BlobType) {
-			    		return new BlobInputStreamFactory((Blob)lob).getInputStream();
-			    	}
-			    	else if (lob instanceof ClobType) {
-			    		return new ClobInputStreamFactory((Clob)lob).getInputStream();
-			    	}
-			    	return new SQLXMLInputStreamFactory((SQLXML)lob).getInputStream();
-				}					
-			};
-			InputStream is = isf.getInputStream();
-			OutputStream fsos = new BufferedOutputStream(store.createOutputStream(), IO_BUFFER_SIZE);
-			while(true) {
-				int read = is.read(bytes, 0, 102400);
-				if (read == -1) {
-					break;
-				}
-				length += read;
-				fsos.write(bytes, 0, read);
-			}
-			fsos.close();
-			is.close();
-		} catch (IOException e) {
-			throw new TeiidComponentException(e);
-		}		
-		
-		// re-construct the new lobs based on the file store
-		final long lobOffset = offset;
-		final int lobLength = length;
-		InputStreamFactory isf = new InputStreamFactory() {
-			@Override
-			public InputStream getInputStream() throws IOException {
-				return store.createInputStream(lobOffset, lobLength);
-			}
-		};			
-		
-		try {
-			if (lob instanceof BlobType) {
-				persistedLob = new BlobType(new BlobImpl(isf));
-			}
-			else if (lob instanceof ClobType) {
-				persistedLob = new ClobType(new ClobImpl(isf, ((ClobType)lob).length()));
-			}
-			else {
-				persistedLob = new XMLType(new SQLXMLImpl(isf));
-				((XMLType)persistedLob).setEncoding(((XMLType)lob).getEncoding());
-				((XMLType)persistedLob).setType(((XMLType)lob).getType());
-			}
-		} catch (SQLException e) {
-			throw new TeiidComponentException(e);
-		}		
-		return persistedLob;		
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/LobManager.java (from rev 2803, trunk/engine/src/main/java/org/teiid/common/buffer/LobManager.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/LobManager.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/LobManager.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,181 @@
+/*
+ * 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.common.buffer;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.BaseLob;
+import org.teiid.core.types.BlobImpl;
+import org.teiid.core.types.BlobType;
+import org.teiid.core.types.ClobImpl;
+import org.teiid.core.types.ClobType;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.SQLXMLImpl;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.types.XMLType;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.sql.symbol.Expression;
+
+/**
+ * Tracks lob references so they are not lost during serialization.
+ * TODO: for temp tables we may need to have a copy by value management strategy
+ */
+public class LobManager {
+	private Map<String, Streamable<?>> lobReferences = new ConcurrentHashMap<String, Streamable<?>>();
+
+	public void updateReferences(int[] lobIndexes, List<?> tuple)
+			throws TeiidComponentException {
+		for (int i = 0; i < lobIndexes.length; i++) {
+			Object anObj = tuple.get(lobIndexes[i]);
+			if (!(anObj instanceof Streamable<?>)) {
+				continue;
+			}
+			Streamable lob = (Streamable) anObj;
+			if (lob.getReference() == null) {
+				lob.setReference(getLobReference(lob.getReferenceStreamId()).getReference());
+			} else {
+				String id = lob.getReferenceStreamId();
+				this.lobReferences.put(id, lob);
+			}
+		}
+	}
+	
+    public Streamable<?> getLobReference(String id) throws TeiidComponentException {
+    	Streamable<?> lob = this.lobReferences.get(id);
+    	if (lob == null) {
+    		throw new TeiidComponentException(QueryPlugin.Util.getString("ProcessWorker.wrongdata")); //$NON-NLS-1$
+    	}
+    	return lob;
+    }
+        
+    public static int[] getLobIndexes(List expressions) {
+    	if (expressions == null) {
+    		return null;
+    	}
+		int[] result = new int[expressions.size()];
+		int resultIndex = 0;
+	    for (int i = 0; i < expressions.size(); i++) {
+	    	Expression expr = (Expression) expressions.get(i);
+	        if (DataTypeManager.isLOB(expr.getType()) || expr.getType() == DataTypeManager.DefaultDataClasses.OBJECT) {
+	        	result[resultIndex++] = i;
+	        }
+	    }
+	    if (resultIndex == 0) {
+	    	return null;
+	    }
+	    return Arrays.copyOf(result, resultIndex);
+    }
+
+	public void persist(FileStore lobStore) throws TeiidComponentException {
+		// stream the contents of lob into file store.
+		byte[] bytes = new byte[102400]; // 100k
+
+		for (Map.Entry<String, Streamable<?>> entry : this.lobReferences.entrySet()) {
+			entry.setValue(persistLob(entry.getValue(), lobStore, bytes));
+		}
+	}    
+    
+	private Streamable<?> persistLob(final Streamable<?> lob, final FileStore store, byte[] bytes) throws TeiidComponentException {
+		
+		// if this is already saved to disk just return
+		if (lob.getReference() instanceof BaseLob) {
+			try {
+				BaseLob baseLob = (BaseLob)lob.getReference();
+				InputStreamFactory isf = baseLob.getStreamFactory();
+				if (isf.isPersistent()) {
+					return lob;
+				}
+			} catch (SQLException e) {
+				// go through regular persistence.
+			}
+		}
+		long offset = store.getLength();
+		int length = 0;
+		Streamable<?> persistedLob;
+					
+		try {
+			InputStreamFactory isf = new InputStreamFactory() {
+				@Override
+				public InputStream getInputStream() throws IOException {
+			    	if (lob instanceof BlobType) {
+			    		return new BlobInputStreamFactory((Blob)lob).getInputStream();
+			    	}
+			    	else if (lob instanceof ClobType) {
+			    		return new ClobInputStreamFactory((Clob)lob).getInputStream();
+			    	}
+			    	return new SQLXMLInputStreamFactory((SQLXML)lob).getInputStream();
+				}					
+			};
+			InputStream is = isf.getInputStream();
+			OutputStream fsos = store.createOutputStream();
+			ObjectConverterUtil.write(fsos, is, bytes, -1);
+		} catch (IOException e) {
+			throw new TeiidComponentException(e);
+		}
+		
+		// re-construct the new lobs based on the file store
+		final long lobOffset = offset;
+		final int lobLength = length;
+		InputStreamFactory isf = new InputStreamFactory() {
+			@Override
+			public InputStream getInputStream() throws IOException {
+				return store.createInputStream(lobOffset, lobLength);
+			}
+			
+			@Override
+			public boolean isPersistent() {
+				return true;
+			}
+		};			
+		
+		try {
+			if (lob instanceof BlobType) {
+				persistedLob = new BlobType(new BlobImpl(isf));
+			}
+			else if (lob instanceof ClobType) {
+				persistedLob = new ClobType(new ClobImpl(isf, ((ClobType)lob).length()));
+			}
+			else {
+				persistedLob = new XMLType(new SQLXMLImpl(isf));
+				((XMLType)persistedLob).setEncoding(((XMLType)lob).getEncoding());
+				((XMLType)persistedLob).setType(((XMLType)lob).getType());
+			}
+		} catch (SQLException e) {
+			throw new TeiidComponentException(e);
+		}		
+		return persistedLob;		
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,344 +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.common.buffer;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.util.Assertion;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.logging.MessageLevel;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.sql.symbol.Expression;
-
-
-public class TupleBuffer {
-	
-	/**
-     * Gets the data type names for each of the input expressions, in order.
-     * @param expressions List of Expressions
-     * @return
-     * @since 4.2
-     */
-    public static String[] getTypeNames(List expressions) {
-    	if (expressions == null) {
-    		return null;
-    	}
-        String[] types = new String[expressions.size()];
-        for (ListIterator i = expressions.listIterator(); i.hasNext();) {
-            Expression expr = (Expression)i.next();
-            types[i.previousIndex()] = DataTypeManager.getDataTypeName(expr.getType());
-        }
-        return types;
-    }
-
-	//construction state
-	private BatchManager manager;
-	private String tupleSourceID;
-	private List<?> schema;
-	private String[] types;
-	private int batchSize;
-	
-	private int rowCount;
-	private boolean isFinal;
-    private TreeMap<Integer, BatchManager.ManagedBatch> batches = new TreeMap<Integer, BatchManager.ManagedBatch>();
-	private ArrayList<List<?>> batchBuffer;
-	private boolean removed;
-	private boolean forwardOnly;
-	private boolean prefersMemory;
-
-	private LobManager lobManager;
-	private int[] lobIndexes;
-	private String uuid;
-	private FileStore lobStore;
-	
-	public TupleBuffer(BatchManager manager, String id, List<?> schema, int[] lobIndexes, int batchSize) {
-		this.manager = manager;
-		this.tupleSourceID = id;
-		this.schema = schema;
-		this.types = getTypeNames(schema);
-		this.lobIndexes = lobIndexes;
-		if (this.lobIndexes != null) {
-			this.lobManager = new LobManager();
-			this.lobStore = this.manager.createStorage("_lobs"); //$NON-NLS-1$
-			this.lobStore.setCleanupReference(this);
-		}
-		this.batchSize = batchSize;		
-	}
-	
-	public String getId() {
-		if (this.uuid == null) {
-			this.uuid = java.util.UUID.randomUUID().toString();
-		}
-		return this.uuid;
-	}	
-	
-	public boolean isLobs() {
-		return lobIndexes != null;
-	}
-	
-	public void addTuple(List<?> tuple) throws TeiidComponentException {
-		if (isLobs()) {
-			lobManager.updateReferences(lobIndexes, tuple);
-		}
-		this.rowCount++;
-		if (batchBuffer == null) {
-			batchBuffer = new ArrayList<List<?>>(batchSize/4);
-		}
-		batchBuffer.add(tuple);
-		if (batchBuffer.size() == batchSize) {
-			saveBatch(false, false);
-		}
-	}
-	
-	/**
-	 * Adds the given batch preserving row offsets.
-	 * @param batch
-	 * @throws TeiidComponentException
-	 */
-	public void addTupleBatch(TupleBatch batch, boolean save) throws TeiidComponentException {
-		setRowCount(batch.getBeginRow() - 1); 
-		if (save) {
-			for (List<?> tuple : batch.getTuples()) {
-				addTuple(tuple);
-			}
-		} else {
-			//add the lob references only, since they may still be referenced later
-			if (isLobs()) {
-				for (List<?> tuple : batch.getTuples()) {
-					lobManager.updateReferences(lobIndexes, tuple);
-				}
-			}
-		}
-	}
-
-	public void setRowCount(int rowCount)
-			throws TeiidComponentException {
-		assert this.rowCount <= rowCount;
-		if (this.rowCount != rowCount) {
-			saveBatch(false, true);
-			this.rowCount = rowCount;
-		}
-	}
-	
-	public void purge() {
-		if (this.batchBuffer != null) {
-			this.batchBuffer.clear();
-		}
-		for (BatchManager.ManagedBatch batch : this.batches.values()) {
-			batch.remove();
-		}
-		this.batches.clear();
-	}
-	
-	public void persistLobs() throws TeiidComponentException {
-		if (this.lobManager != null) {
-			saveBatch(true, true);
-			this.lobManager.persist(this.lobStore);
-		}
-	}
-	
-	/**
-	 * Force the persistence of any rows held in memory.
-	 * @throws TeiidComponentException
-	 */
-	public void saveBatch() throws TeiidComponentException {
-		this.saveBatch(false, false);
-	}
-
-	void saveBatch(boolean finalBatch, boolean force) throws TeiidComponentException {
-		Assertion.assertTrue(!this.isRemoved());
-		if (batchBuffer == null || batchBuffer.isEmpty() || (!force && batchBuffer.size() < Math.max(1, batchSize / 32))) {
-			return;
-		}
-        TupleBatch writeBatch = new TupleBatch(rowCount - batchBuffer.size() + 1, batchBuffer);
-        if (finalBatch) {
-        	writeBatch.setTerminationFlag(true);
-        }
-        writeBatch.setDataTypes(types);
-		BatchManager.ManagedBatch mbatch = manager.createManagedBatch(writeBatch, prefersMemory);
-		this.batches.put(writeBatch.getBeginRow(), mbatch);
-        batchBuffer = null;
-	}
-	
-	public void close() throws TeiidComponentException {
-		saveBatch(true, false);
-		this.isFinal = true;
-	}
-	
-	/**
-	 * Get the batch containing the given row.
-	 * NOTE: the returned batch may be empty or may begin with a row other
-	 * than the one specified.
-	 * @param row
-	 * @return
-	 * @throws TeiidComponentException
-	 */
-	public TupleBatch getBatch(int row) throws TeiidComponentException {
-		TupleBatch result = null;
-		if (row > rowCount) {
-			result = new TupleBatch(rowCount + 1, new List[] {});
-		} else if (this.batchBuffer != null && row > rowCount - this.batchBuffer.size()) {
-			result = new TupleBatch(rowCount - this.batchBuffer.size() + 1, batchBuffer);
-			if (forwardOnly) {
-				this.batchBuffer = null;
-			}
-		} else {
-			if (this.batchBuffer != null && !this.batchBuffer.isEmpty()) {
-				//this is just a sanity check to ensure we're not holding too many
-				//hard references to batches.
-				saveBatch(isFinal, false);
-			}
-			Map.Entry<Integer, BatchManager.ManagedBatch> entry = batches.floorEntry(row);
-			Assertion.isNotNull(entry);
-			BatchManager.ManagedBatch batch = entry.getValue();
-	    	result = batch.getBatch(!forwardOnly, types);
-	    	if (forwardOnly) {
-				batches.remove(entry.getKey());
-			}
-		}
-		result.setDataTypes(types);
-		if (isFinal && result.getEndRow() == rowCount) {
-			result.setTerminationFlag(true);
-		}
-		return result;
-	}
-	
-	public void remove() {
-		if (!removed) {
-			if (LogManager.isMessageToBeRecorded(LogConstants.CTX_BUFFER_MGR, MessageLevel.DETAIL)) {
-	            LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Removing TupleBuffer:", this.tupleSourceID); //$NON-NLS-1$
-	        }
-			this.batchBuffer = null;
-			purge();
-			this.manager.remove();
-			removed = true;
-		}
-	}
-	
-	public int getRowCount() {
-		return rowCount;
-	}
-	
-	public boolean isFinal() {
-		return isFinal;
-	}
-	
-	public void setFinal(boolean isFinal) {
-		this.isFinal = isFinal;
-	}
-	
-	public List<?> getSchema() {
-		return schema;
-	}
-	
-	public int getBatchSize() {
-		return batchSize;
-	}
-	
-	public void setBatchSize(int batchSize) {
-		this.batchSize = batchSize;
-	}
-	    
-    public Streamable<?> getLobReference(String id) throws TeiidComponentException {
-    	if (lobManager == null) {
-    		throw new TeiidComponentException(QueryPlugin.Util.getString("ProcessWorker.wrongdata")); //$NON-NLS-1$
-    	}
-    	return lobManager.getLobReference(id);
-    }
-    
-    public void setForwardOnly(boolean forwardOnly) {
-		this.forwardOnly = forwardOnly;
-	}
-    
-	public IndexedTupleSource createIndexedTupleSource() {
-		return createIndexedTupleSource(false);
-	}
-    
-	/**
-	 * Create a new iterator for this buffer
-	 * @return
-	 */
-	public IndexedTupleSource createIndexedTupleSource(final boolean singleUse) {
-		if (singleUse) {
-			setForwardOnly(true);
-		}
-		return new AbstractTupleSource() {
-			
-			@Override
-			protected List<?> finalRow() throws BlockedException {
-				if(isFinal) {
-		            return null;
-		        } 
-		        throw BlockedException.INSTANCE;
-			}
-			
-			@Override
-			public int available() {
-				return rowCount - getCurrentIndex() + 1;
-			}
-			
-			@Override
-			protected TupleBatch getBatch(int row) throws TeiidComponentException {
-				return TupleBuffer.this.getBatch(row);
-			}
-			
-			@Override
-			public void closeSource() {
-				super.closeSource();
-				if (singleUse) {
-					remove();
-				}
-			}
-		};
-	}
-	
-	@Override
-	public String toString() {
-		return this.tupleSourceID;
-	}
-	
-	public boolean isRemoved() {
-		return removed;
-	}
-	
-	public boolean isForwardOnly() {
-		return forwardOnly;
-	}
-	
-	public void setPrefersMemory(boolean prefersMemory) {
-		this.prefersMemory = prefersMemory;
-	}
-	
-	public boolean isPrefersMemory() {
-		return prefersMemory;
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java (from rev 2803, trunk/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,346 @@
+/*
+ * 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.common.buffer;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.util.Assertion;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.sql.symbol.Expression;
+
+
+public class TupleBuffer {
+	
+	/**
+     * Gets the data type names for each of the input expressions, in order.
+     * @param expressions List of Expressions
+     * @return
+     * @since 4.2
+     */
+    public static String[] getTypeNames(List expressions) {
+    	if (expressions == null) {
+    		return null;
+    	}
+        String[] types = new String[expressions.size()];
+        for (ListIterator i = expressions.listIterator(); i.hasNext();) {
+            Expression expr = (Expression)i.next();
+            types[i.previousIndex()] = DataTypeManager.getDataTypeName(expr.getType());
+        }
+        return types;
+    }
+
+	//construction state
+	private BatchManager manager;
+	private String tupleSourceID;
+	private List<?> schema;
+	private String[] types;
+	private int batchSize;
+	
+	private int rowCount;
+	private boolean isFinal;
+    private TreeMap<Integer, BatchManager.ManagedBatch> batches = new TreeMap<Integer, BatchManager.ManagedBatch>();
+	private ArrayList<List<?>> batchBuffer;
+	private boolean removed;
+	private boolean forwardOnly;
+	private boolean prefersMemory;
+
+	private LobManager lobManager;
+	private int[] lobIndexes;
+	private String uuid;
+	private FileStore lobStore;
+	
+	public TupleBuffer(BatchManager manager, String id, List<?> schema, int[] lobIndexes, int batchSize) {
+		this.manager = manager;
+		this.tupleSourceID = id;
+		this.schema = schema;
+		this.types = getTypeNames(schema);
+		this.lobIndexes = lobIndexes;
+		if (this.lobIndexes != null) {
+			this.lobManager = new LobManager();
+			this.lobStore = this.manager.createStorage("_lobs"); //$NON-NLS-1$
+			this.lobStore.setCleanupReference(this);
+		}
+		this.batchSize = batchSize;		
+	}
+	
+	public String getId() {
+		if (this.uuid == null) {
+			this.uuid = java.util.UUID.randomUUID().toString();
+		}
+		return this.uuid;
+	}	
+	
+	public boolean isLobs() {
+		return lobIndexes != null;
+	}
+	
+	public void addTuple(List<?> tuple) throws TeiidComponentException {
+		if (isLobs()) {
+			lobManager.updateReferences(lobIndexes, tuple);
+		}
+		this.rowCount++;
+		if (batchBuffer == null) {
+			batchBuffer = new ArrayList<List<?>>(batchSize/4);
+		}
+		batchBuffer.add(tuple);
+		if (batchBuffer.size() == batchSize) {
+			saveBatch(false, false);
+		}
+	}
+	
+	/**
+	 * Adds the given batch preserving row offsets.
+	 * @param batch
+	 * @throws TeiidComponentException
+	 */
+	public void addTupleBatch(TupleBatch batch, boolean save) throws TeiidComponentException {
+		setRowCount(batch.getBeginRow() - 1); 
+		if (save) {
+			for (List<?> tuple : batch.getTuples()) {
+				addTuple(tuple);
+			}
+		} else {
+			//add the lob references only, since they may still be referenced later
+			if (isLobs()) {
+				for (List<?> tuple : batch.getTuples()) {
+					lobManager.updateReferences(lobIndexes, tuple);
+				}
+			}
+		}
+	}
+
+	public void setRowCount(int rowCount)
+			throws TeiidComponentException {
+		assert this.rowCount <= rowCount;
+		if (this.rowCount != rowCount) {
+			saveBatch(false, true);
+			this.rowCount = rowCount;
+		}
+	}
+	
+	public void purge() {
+		if (this.batchBuffer != null) {
+			this.batchBuffer.clear();
+		}
+		for (BatchManager.ManagedBatch batch : this.batches.values()) {
+			batch.remove();
+		}
+		this.batches.clear();
+	}
+	
+	public void persistLobs() throws TeiidComponentException {
+		if (this.lobManager != null) {
+			this.lobManager.persist(this.lobStore);
+		}
+	}
+	
+	/**
+	 * Force the persistence of any rows held in memory.
+	 * @throws TeiidComponentException
+	 */
+	public void saveBatch() throws TeiidComponentException {
+		this.saveBatch(false, false);
+	}
+
+	void saveBatch(boolean finalBatch, boolean force) throws TeiidComponentException {
+		Assertion.assertTrue(!this.isRemoved());
+		if (batchBuffer == null || batchBuffer.isEmpty() || (!force && batchBuffer.size() < Math.max(1, batchSize / 32))) {
+			return;
+		}
+        TupleBatch writeBatch = new TupleBatch(rowCount - batchBuffer.size() + 1, batchBuffer);
+        if (finalBatch) {
+        	writeBatch.setTerminationFlag(true);
+        }
+        writeBatch.setDataTypes(types);
+		BatchManager.ManagedBatch mbatch = manager.createManagedBatch(writeBatch, prefersMemory);
+		this.batches.put(writeBatch.getBeginRow(), mbatch);
+        batchBuffer = null;
+	}
+	
+	public void close() throws TeiidComponentException {
+		saveBatch(true, false);
+		this.isFinal = true;
+	}
+	
+	/**
+	 * Get the batch containing the given row.
+	 * NOTE: the returned batch may be empty or may begin with a row other
+	 * than the one specified.
+	 * @param row
+	 * @return
+	 * @throws TeiidComponentException
+	 */
+	public TupleBatch getBatch(int row) throws TeiidComponentException {
+		TupleBatch result = null;
+		if (row > rowCount) {
+			result = new TupleBatch(rowCount + 1, new List[] {});
+		} else if (this.batchBuffer != null && row > rowCount - this.batchBuffer.size()) {
+			result = new TupleBatch(rowCount - this.batchBuffer.size() + 1, batchBuffer);
+			if (forwardOnly) {
+				this.batchBuffer = null;
+			}
+		} else {
+			if (this.batchBuffer != null && !this.batchBuffer.isEmpty()) {
+				//this is just a sanity check to ensure we're not holding too many
+				//hard references to batches.
+				saveBatch(isFinal, false);
+			}
+			Map.Entry<Integer, BatchManager.ManagedBatch> entry = batches.floorEntry(row);
+			Assertion.isNotNull(entry);
+			BatchManager.ManagedBatch batch = entry.getValue();
+	    	result = batch.getBatch(!forwardOnly, types);
+	    	if (forwardOnly) {
+				batches.remove(entry.getKey());
+			}
+		}
+		result.setDataTypes(types);
+		if (isFinal && result.getEndRow() == rowCount) {
+			result.setTerminationFlag(true);
+		}
+		return result;
+	}
+	
+	public void remove() {
+		if (!removed) {
+			if (LogManager.isMessageToBeRecorded(LogConstants.CTX_BUFFER_MGR, MessageLevel.DETAIL)) {
+	            LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Removing TupleBuffer:", this.tupleSourceID); //$NON-NLS-1$
+	        }
+			if (this.lobStore != null) {
+				this.lobStore.remove();
+			}
+			this.batchBuffer = null;
+			purge();
+			this.manager.remove();
+			removed = true;
+		}
+	}
+	
+	public int getRowCount() {
+		return rowCount;
+	}
+	
+	public boolean isFinal() {
+		return isFinal;
+	}
+	
+	public void setFinal(boolean isFinal) {
+		this.isFinal = isFinal;
+	}
+	
+	public List<?> getSchema() {
+		return schema;
+	}
+	
+	public int getBatchSize() {
+		return batchSize;
+	}
+	
+	public void setBatchSize(int batchSize) {
+		this.batchSize = batchSize;
+	}
+	    
+    public Streamable<?> getLobReference(String id) throws TeiidComponentException {
+    	if (lobManager == null) {
+    		throw new TeiidComponentException(QueryPlugin.Util.getString("ProcessWorker.wrongdata")); //$NON-NLS-1$
+    	}
+    	return lobManager.getLobReference(id);
+    }
+    
+    public void setForwardOnly(boolean forwardOnly) {
+		this.forwardOnly = forwardOnly;
+	}
+    
+	public IndexedTupleSource createIndexedTupleSource() {
+		return createIndexedTupleSource(false);
+	}
+    
+	/**
+	 * Create a new iterator for this buffer
+	 * @return
+	 */
+	public IndexedTupleSource createIndexedTupleSource(final boolean singleUse) {
+		if (singleUse) {
+			setForwardOnly(true);
+		}
+		return new AbstractTupleSource() {
+			
+			@Override
+			protected List<?> finalRow() throws BlockedException {
+				if(isFinal) {
+		            return null;
+		        } 
+		        throw BlockedException.INSTANCE;
+			}
+			
+			@Override
+			public int available() {
+				return rowCount - getCurrentIndex() + 1;
+			}
+			
+			@Override
+			protected TupleBatch getBatch(int row) throws TeiidComponentException {
+				return TupleBuffer.this.getBatch(row);
+			}
+			
+			@Override
+			public void closeSource() {
+				super.closeSource();
+				if (singleUse) {
+					remove();
+				}
+			}
+		};
+	}
+	
+	@Override
+	public String toString() {
+		return this.tupleSourceID;
+	}
+	
+	public boolean isRemoved() {
+		return removed;
+	}
+	
+	public boolean isForwardOnly() {
+		return forwardOnly;
+	}
+	
+	public void setPrefersMemory(boolean prefersMemory) {
+		this.prefersMemory = prefersMemory;
+	}
+	
+	public boolean isPrefersMemory() {
+		return prefersMemory;
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,638 +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.common.buffer.impl;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.lang.ref.WeakReference;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import org.teiid.common.buffer.BatchManager;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.FileStore;
-import org.teiid.common.buffer.LobManager;
-import org.teiid.common.buffer.STree;
-import org.teiid.common.buffer.StorageManager;
-import org.teiid.common.buffer.TupleBatch;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.common.buffer.BatchManager.ManagedBatch;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.util.Assertion;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.processor.relational.ListNestedSortComparator;
-
-
-/**
- * <p>Default implementation of BufferManager.</p>
- * Responsible for creating/tracking TupleBuffers and providing access to the StorageManager.
- * </p>
- * The buffering strategy attempts to purge batches from the least recently used TupleBuffer
- * from before (which wraps around circularly) the last used batch.  This attempts to compensate 
- * for our tendency to read buffers in a forward manner.  If our processing algorithms are changed 
- * to use alternating ascending/descending access, then the buffering approach could be replaced 
- * with a simple LRU.
- * 
- * TODO: allow for cached stores to use lru - (result set/mat view)
- * TODO: account for row/content based sizing (difficult given value sharing)
- * TODO: account for memory based lobs (it would be nice if the approximate buffer size matched at 100kB)
- * TODO: add detection of pinned batches to prevent unnecessary purging of non-persistent batches
- *       - this is not necessary for already persistent batches, since we hold a weak reference
- */
-public class BufferManagerImpl implements BufferManager, StorageManager {
-	
-	private static final int IO_BUFFER_SIZE = 1 << 14;
-	private static final int COMPACTION_THRESHOLD = 1 << 25; //start checking at 32 megs
-	
-	private final class BatchManagerImpl implements BatchManager {
-		private final String id;
-		private final int columnCount;
-		private volatile FileStore store;
-		private Map<Long, long[]> physicalMapping = new ConcurrentHashMap<Long, long[]>();
-		private ReadWriteLock compactionLock = new ReentrantReadWriteLock();
-		private AtomicLong unusedSpace = new AtomicLong();
-		private int[] lobIndexes;
-
-		private BatchManagerImpl(String newID, int columnCount, int[] lobIndexes) {
-			this.id = newID;
-			this.columnCount = columnCount;
-			this.store = createFileStore(id);
-			this.store.setCleanupReference(this);
-			this.lobIndexes = lobIndexes;
-		}
-		
-		public FileStore createStorage(String prefix) {
-			return createFileStore(id+prefix);
-		}
-
-		@Override
-		public ManagedBatch createManagedBatch(TupleBatch batch, boolean softCache)
-				throws TeiidComponentException {
-			ManagedBatchImpl mbi = new ManagedBatchImpl(batch, this, softCache);
-			mbi.addToCache(false);
-			persistBatchReferences();
-			return mbi;
-		}
-		
-		private boolean shouldCompact(long offset) {
-			return offset > COMPACTION_THRESHOLD && unusedSpace.get() * 4 > offset * 3;
-		}
-		
-		private long getOffset() throws TeiidComponentException {
-			long offset = store.getLength();
-			if (!shouldCompact(offset)) {
-				return offset;
-			}
-			try {
-				this.compactionLock.writeLock().lock();
-				offset = store.getLength();
-				//retest the condition to ensure that compaction is still needed
-				if (!shouldCompact(offset)) {
-					return offset;
-				}
-				FileStore newStore = createFileStore(id);
-				newStore.setCleanupReference(this);
-				byte[] buffer = new byte[IO_BUFFER_SIZE];
-				List<long[]> values = new ArrayList<long[]>(physicalMapping.values());
-				Collections.sort(values, new Comparator<long[]>() {
-					@Override
-					public int compare(long[] o1, long[] o2) {
-						return Long.signum(o1[0] - o2[0]);
-					}
-				});
-				for (long[] info : values) {
-					long oldOffset = info[0];
-					info[0] = newStore.getLength();
-					int size = (int)info[1];
-					while (size > 0) {
-						int toWrite = Math.min(IO_BUFFER_SIZE, size);
-						store.readFully(oldOffset, buffer, 0, toWrite);
-						newStore.write(buffer, 0, toWrite);
-						size -= toWrite;
-					}
-				}
-				store.remove();
-				store = newStore;
-				long oldOffset = offset;
-				offset = store.getLength();
-				LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, "Compacted store", id, "pre-size", oldOffset, "post-size", offset); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-				return offset;
-			} finally {
-				this.compactionLock.writeLock().unlock();
-			}
-		}
-
-		@Override
-		public void remove() {
-			this.store.remove();
-		}
-	}
-
-	/**
-	 * Holder for active batches
-	 */
-	private class TupleBufferInfo {
-		TreeMap<Integer, ManagedBatchImpl> batches = new TreeMap<Integer, ManagedBatchImpl>();
-		Integer lastUsed = null;
-		
-		ManagedBatchImpl removeBatch(int row) {
-			ManagedBatchImpl result = batches.remove(row);
-			if (result != null) {
-				activeBatchColumnCount -= result.batchManager.columnCount;
-			}
-			return result;
-		}
-	}
-	
-	private final class ManagedBatchImpl implements ManagedBatch {
-		private boolean persistent;
-		private boolean softCache;
-		private volatile TupleBatch activeBatch;
-		private volatile Reference<TupleBatch> batchReference;
-		private int beginRow;
-		private BatchManagerImpl batchManager;
-		private long id;
-		private LobManager lobManager;
-		
-		public ManagedBatchImpl(TupleBatch batch, BatchManagerImpl manager, boolean softCache) {
-			this.softCache = softCache;
-			id = batchAdded.incrementAndGet();
-            LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, "Add batch to BufferManager", id); //$NON-NLS-1$
-			this.activeBatch = batch;
-			this.beginRow = batch.getBeginRow();
-			this.batchManager = manager;
-			if (this.batchManager.lobIndexes != null) {
-				this.lobManager = new LobManager();
-			}
-		}
-
-		private void addToCache(boolean update) {
-			synchronized (activeBatches) {
-				TupleBatch batch = this.activeBatch;
-				if (batch == null) {
-					return; //already removed
-				}
-				activeBatchColumnCount += batchManager.columnCount;
-				TupleBufferInfo tbi = null;
-				if (update) {
-					tbi = activeBatches.remove(batchManager.id);
-				} else {
-					tbi = activeBatches.get(batchManager.id);
-				}
-				if (tbi == null) {
-					tbi = new TupleBufferInfo();
-					update = true;
-				} 
-				if (update) {
-					activeBatches.put(batchManager.id, tbi);
-				}
-				Assertion.isNull(tbi.batches.put(this.beginRow, this));
-			}
-		}
-
-		@Override
-		public TupleBatch getBatch(boolean cache, String[] types) throws TeiidComponentException {
-			long reads = readAttempts.incrementAndGet();
-			LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, batchManager.id, "getting batch", reads, "reference hits", referenceHit.get()); //$NON-NLS-1$ //$NON-NLS-2$
-			synchronized (activeBatches) {
-				TupleBufferInfo tbi = activeBatches.remove(batchManager.id);
-				if (tbi != null) { 
-					boolean put = true;
-					if (!cache) {
-						tbi.removeBatch(this.beginRow);
-						if (tbi.batches.isEmpty()) {
-							put = false;
-						}
-					}
-					if (put) {
-						tbi.lastUsed = this.beginRow;
-						activeBatches.put(batchManager.id, tbi);
-					}
-				}
-			}
-			persistBatchReferences();
-			synchronized (this) {
-				TupleBatch batch = this.activeBatch;
-				if (batch != null){
-					return batch;
-				}
-				Reference<TupleBatch> ref = this.batchReference;
-				this.batchReference = null;
-				if (ref != null) {
-					batch = ref.get();
-					if (batch != null) {
-						if (cache) {
-							this.activeBatch = batch;
-				        	addToCache(true);
-						} 
-						referenceHit.getAndIncrement();
-						return batch;
-					}
-				}
-				long count = readCount.incrementAndGet();
-				LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, batchManager.id, id, "reading batch from disk, total reads:", count); //$NON-NLS-1$
-				try {
-					this.batchManager.compactionLock.readLock().lock();
-					long[] info = batchManager.physicalMapping.get(this.id);
-					ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(batchManager.store.createInputStream(info[0]), IO_BUFFER_SIZE));
-		            batch = new TupleBatch();
-		            batch.setDataTypes(types);
-		            batch.readExternal(ois);
-		            batch.setRowOffset(this.beginRow);
-			        batch.setDataTypes(null);
-					if (lobManager != null) {
-						for (List<?> tuple : batch.getTuples()) {
-							lobManager.updateReferences(batchManager.lobIndexes, tuple);
-						}
-					}
-			        if (cache) {
-			        	this.activeBatch = batch;
-			        	addToCache(true);
-			        }
-					return batch;
-		        } catch(IOException e) {
-		        	throw new TeiidComponentException(e, QueryPlugin.Util.getString("FileStoreageManager.error_reading", batchManager.id)); //$NON-NLS-1$
-		        } catch (ClassNotFoundException e) {
-		        	throw new TeiidComponentException(e, QueryPlugin.Util.getString("FileStoreageManager.error_reading", batchManager.id)); //$NON-NLS-1$
-		        } finally {
-		        	this.batchManager.compactionLock.readLock().unlock();
-		        }
-			}
-		}
-
-		public synchronized void persist() throws TeiidComponentException {
-			boolean lockheld = false;
-            try {
-				TupleBatch batch = activeBatch;
-				if (batch != null) {
-					if (!persistent) {
-						long count = writeCount.incrementAndGet();
-						LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, batchManager.id, id, "writing batch to disk, total writes: ", count); //$NON-NLS-1$
-						long offset = 0;
-						if (lobManager != null) {
-							for (List<?> tuple : batch.getTuples()) {
-								lobManager.updateReferences(batchManager.lobIndexes, tuple);
-								Collection<Streamable<?>> lobs = lobManager.getLobReferences();
-								for(Streamable<?> lob: lobs) {
-						            lobManager.persist(lob.getReferenceStreamId(), batchManager.store);
-								}
-							}
-						}
-						synchronized (batchManager.store) {
-							offset = batchManager.getOffset();
-							OutputStream fsos = new BufferedOutputStream(batchManager.store.createOutputStream(), IO_BUFFER_SIZE);
-				            ObjectOutputStream oos = new ObjectOutputStream(fsos);
-				            batch.writeExternal(oos);
-				            oos.close();
-				            long size = batchManager.store.getLength() - offset;
-				            long[] info = new long[] {offset, size};
-				            batchManager.physicalMapping.put(this.id, info);
-						}
-						LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, batchManager.id, id, "batch written starting at:", offset); //$NON-NLS-1$
-					}
-					if (softCache) {
-						this.batchReference = new SoftReference<TupleBatch>(batch);
-					} else {
-						this.batchReference = new WeakReference<TupleBatch>(batch);
-					}
-				}
-			} catch (IOException e) {
-				throw new TeiidComponentException(e);
-			} catch (Throwable e) {
-				throw new TeiidComponentException(e);
-			} finally {
-				persistent = true;
-				activeBatch = null;
-				if (lockheld) {
-					this.batchManager.compactionLock.writeLock().unlock();
-				}
-			}
-		}
-
-		public void remove() {
-			synchronized (activeBatches) {
-				TupleBufferInfo tbi = activeBatches.get(batchManager.id);
-				if (tbi != null && tbi.removeBatch(this.beginRow) != null) {
-					if (tbi.batches.isEmpty()) {
-						activeBatches.remove(batchManager.id);
-					}
-				}
-			}
-			long[] info = batchManager.physicalMapping.remove(id);
-			if (info != null) {
-				batchManager.unusedSpace.addAndGet(info[1]); 
-			}
-			if (lobManager != null) {
-				lobManager.clear();
-			}
-			activeBatch = null;
-			batchReference = null;
-		}
-		
-		@Override
-		public String toString() {
-			return "ManagedBatch " + batchManager.id + " " + activeBatch; //$NON-NLS-1$ //$NON-NLS-2$
-		}
-	}
-	
-	// Configuration 
-    private int connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
-    private int processorBatchSize = BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE;
-    private int maxProcessingBatches = BufferManager.DEFAULT_MAX_PROCESSING_BATCHES;
-    private int maxReserveBatchColumns = BufferManager.DEFAULT_RESERVE_BUFFERS;
-    private volatile int reserveBatchColumns = BufferManager.DEFAULT_RESERVE_BUFFERS;
-    
-    private ReentrantLock lock = new ReentrantLock(true);
-    private Condition batchesFreed = lock.newCondition();
-    
-    private volatile int activeBatchColumnCount = 0;
-    private Map<String, TupleBufferInfo> activeBatches = new LinkedHashMap<String, TupleBufferInfo>();
-	private Map<String, TupleReference> tupleBufferMap = new ConcurrentHashMap<String, TupleReference>();
-	private ReferenceQueue<TupleBuffer> tupleBufferQueue = new ReferenceQueue<TupleBuffer>();
-    
-    
-    private StorageManager diskMgr;
-
-    private AtomicLong tsId = new AtomicLong();
-    private AtomicLong batchAdded = new AtomicLong();
-    private AtomicLong readCount = new AtomicLong();
-	private AtomicLong writeCount = new AtomicLong();
-	private AtomicLong readAttempts = new AtomicLong();
-	private AtomicLong referenceHit = new AtomicLong();
-	
-	public long getBatchesAdded() {
-		return batchAdded.get();
-	}
-	
-	public long getReadCount() {
-		return readCount.get();
-	}
-	
-	public long getWriteCount() {
-		return writeCount.get();
-	}
-	
-	public long getReadAttempts() {
-		return readAttempts.get();
-	}
-	
-	@Override
-    public int getMaxProcessingBatchColumns() {
-		return maxProcessingBatches;
-	}
-    
-    public void setMaxProcessingBatchColumns(int maxProcessingBatches) {
-		this.maxProcessingBatches = Math.max(0, maxProcessingBatches);
-	}
-
-    /**
-     * Get processor batch size
-     * @return Number of rows in a processor batch
-     */
-    @Override
-    public int getProcessorBatchSize() {        
-        return this.processorBatchSize;
-    }
-
-    /**
-     * Get connector batch size
-     * @return Number of rows in a connector batch
-     */
-    @Override
-    public int getConnectorBatchSize() {
-        return this.connectorBatchSize;
-    }
-    
-    public void setConnectorBatchSize(int connectorBatchSize) {
-        this.connectorBatchSize = connectorBatchSize;
-    } 
-
-    public void setProcessorBatchSize(int processorBatchSize) {
-        this.processorBatchSize = processorBatchSize;
-    } 
-
-    /**
-     * Add a storage manager to this buffer manager, order is unimportant
-     * @param storageManager Storage manager to add
-     */
-    public void setStorageManager(StorageManager storageManager) {
-    	Assertion.isNotNull(storageManager);
-    	Assertion.isNull(diskMgr);
-        this.diskMgr = storageManager;
-    }
-    
-    public StorageManager getStorageManager() {
-		return diskMgr;
-	}
-    
-    @Override
-    public TupleBuffer createTupleBuffer(final List elements, String groupName,
-    		TupleSourceType tupleSourceType) {
-    	final String newID = String.valueOf(this.tsId.getAndIncrement());
-    	int[] lobIndexes = LobManager.getLobIndexes(elements);
-    	BatchManager batchManager = new BatchManagerImpl(newID, elements.size(), lobIndexes);
-        TupleBuffer tupleBuffer = new TupleBuffer(batchManager, newID, elements, lobIndexes, getProcessorBatchSize());
-        LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Creating TupleBuffer:", newID, "of type ", tupleSourceType); //$NON-NLS-1$ //$NON-NLS-2$
-        return tupleBuffer;
-    }
-    
-    public STree createSTree(final List elements, String groupName, int keyLength) {
-    	String newID = String.valueOf(this.tsId.getAndIncrement());
-    	int[] lobIndexes = LobManager.getLobIndexes(elements);
-    	BatchManager bm = new BatchManagerImpl(newID, elements.size(), lobIndexes);
-    	BatchManager keyManager = new BatchManagerImpl(String.valueOf(this.tsId.getAndIncrement()), keyLength, null);
-    	int[] compareIndexes = new int[keyLength];
-    	for (int i = 1; i < compareIndexes.length; i++) {
-			compareIndexes[i] = i;
-		}
-        LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Creating STree:", newID); //$NON-NLS-1$ 
-    	return new STree(keyManager, bm, new ListNestedSortComparator(compareIndexes), getProcessorBatchSize(), keyLength, TupleBuffer.getTypeNames(elements));
-    }
-
-    @Override
-    public FileStore createFileStore(String name) {
-        LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Creating FileStore:", name); //$NON-NLS-1$ 
-    	return this.diskMgr.createFileStore(name);
-    }
-    
-	@Override
-	public void initialize() throws TeiidComponentException {
-		
-	}
-	
-    @Override
-    public void releaseBuffers(int count) {
-    	if (count < 1) {
-    		return;
-    	}
-    	lock.lock();
-    	try {
-	    	this.reserveBatchColumns += count;
-	    	batchesFreed.signalAll();
-    	} finally {
-    		lock.unlock();
-    	}
-    }	
-    
-    @Override
-    public int reserveBuffers(int count, BufferReserveMode mode) {
-    	lock.lock();
-	    try {
-	    	if (mode == BufferReserveMode.WAIT) {
-		    	int waitCount = 0;
-		    	while (count - waitCount > this.reserveBatchColumns) {
-		    		try {
-						batchesFreed.await(100, TimeUnit.MILLISECONDS);
-					} catch (InterruptedException e) {
-						throw new TeiidRuntimeException(e);
-					}
-					waitCount++;
-		    	}	
-	    	}
-	    	if (this.reserveBatchColumns >= count || mode == BufferReserveMode.FORCE) {
-		    	this.reserveBatchColumns -= count;
-	    		return count;
-	    	}
-	    	int result = Math.max(0, this.reserveBatchColumns);
-	    	this.reserveBatchColumns -= result;
-	    	return result;
-	    } finally {
-    		lock.unlock();
-    		persistBatchReferences();
-    	}
-    }
-    
-	void persistBatchReferences() {
-		if (activeBatchColumnCount == 0 || activeBatchColumnCount <= reserveBatchColumns) {
-			int memoryCount = activeBatchColumnCount + maxReserveBatchColumns - reserveBatchColumns;
-			if (DataTypeManager.isValueCacheEnabled()) {
-				if (memoryCount < maxReserveBatchColumns / 8) {
-					DataTypeManager.setValueCacheEnabled(false);
-				}
-			} else if (memoryCount > maxReserveBatchColumns / 4) {
-				DataTypeManager.setValueCacheEnabled(true);
-			}
-			return;
-		}
-		while (true) {
-			ManagedBatchImpl mb = null;
-			synchronized (activeBatches) {
-				if (activeBatchColumnCount == 0 || activeBatchColumnCount * 5 < reserveBatchColumns * 4) {
-					break;
-				}
-				Iterator<TupleBufferInfo> iter = activeBatches.values().iterator();
-				TupleBufferInfo tbi = iter.next();
-				Map.Entry<Integer, ManagedBatchImpl> entry = null;
-				if (tbi.lastUsed != null) {
-					entry = tbi.batches.floorEntry(tbi.lastUsed - 1);
-				}
-				if (entry == null) {
-					entry = tbi.batches.lastEntry();
-				} 
-				tbi.removeBatch(entry.getKey());
-				if (tbi.batches.isEmpty()) {
-					iter.remove();
-				}
-				mb = entry.getValue();
-			}
-			try {
-				mb.persist();
-			} catch (TeiidComponentException e) {
-				LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, e, "Error persisting batch, attempts to read that batch later will result in an exception"); //$NON-NLS-1$
-			}
-		}
-	}
-	
-	@Override
-	public int getSchemaSize(List elements) {
-		return elements.size();
-	}
-	
-    public void setMaxReserveBatchColumns(int maxReserve) {
-    	this.maxReserveBatchColumns = maxReserve;
-		this.reserveBatchColumns = maxReserve;
-	}
-
-	public void shutdown() {
-	}
-
-	@Override
-	public void addTupleBuffer(TupleBuffer tb) {
-		cleanDefunctTupleBuffers();
-		this.tupleBufferMap.put(tb.getId(), new TupleReference(tb, this.tupleBufferQueue));
-	}
-	
-	@Override
-	public TupleBuffer getTupleBuffer(String id) {		
-		cleanDefunctTupleBuffers();
-		Reference<TupleBuffer> r = this.tupleBufferMap.get(id);
-		if (r != null) {
-			return r.get();
-		}
-		return null;
-	}
-	
-	private void cleanDefunctTupleBuffers() {
-		while (true) {
-			Reference r = this.tupleBufferQueue.poll();
-			if (r == null) {
-				break;
-			}
-			this.tupleBufferMap.remove(((TupleReference)r).id);
-		}
-	}
-	
-	static class TupleReference extends WeakReference<TupleBuffer>{
-		String id;
-		public TupleReference(TupleBuffer referent, ReferenceQueue<? super TupleBuffer> q) {
-			super(referent, q);
-			id = referent.getId();
-		}
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java (from rev 2803, trunk/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,629 @@
+/*
+ * 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.common.buffer.impl;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import org.teiid.common.buffer.BatchManager;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.FileStore;
+import org.teiid.common.buffer.LobManager;
+import org.teiid.common.buffer.STree;
+import org.teiid.common.buffer.StorageManager;
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.BatchManager.ManagedBatch;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.Assertion;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.processor.relational.ListNestedSortComparator;
+
+
+/**
+ * <p>Default implementation of BufferManager.</p>
+ * Responsible for creating/tracking TupleBuffers and providing access to the StorageManager.
+ * </p>
+ * The buffering strategy attempts to purge batches from the least recently used TupleBuffer
+ * from before (which wraps around circularly) the last used batch.  This attempts to compensate 
+ * for our tendency to read buffers in a forward manner.  If our processing algorithms are changed 
+ * to use alternating ascending/descending access, then the buffering approach could be replaced 
+ * with a simple LRU.
+ * 
+ * TODO: allow for cached stores to use lru - (result set/mat view)
+ * TODO: account for row/content based sizing (difficult given value sharing)
+ * TODO: account for memory based lobs (it would be nice if the approximate buffer size matched at 100kB)
+ * TODO: add detection of pinned batches to prevent unnecessary purging of non-persistent batches
+ *       - this is not necessary for already persistent batches, since we hold a weak reference
+ */
+public class BufferManagerImpl implements BufferManager, StorageManager {
+	
+	private static final int IO_BUFFER_SIZE = 1 << 14;
+	private static final int COMPACTION_THRESHOLD = 1 << 25; //start checking at 32 megs
+	
+	private final class BatchManagerImpl implements BatchManager {
+		private final String id;
+		private final int columnCount;
+		private volatile FileStore store;
+		private Map<Long, long[]> physicalMapping = new ConcurrentHashMap<Long, long[]>();
+		private ReadWriteLock compactionLock = new ReentrantReadWriteLock();
+		private AtomicLong unusedSpace = new AtomicLong();
+		private int[] lobIndexes;
+
+		private BatchManagerImpl(String newID, int columnCount, int[] lobIndexes) {
+			this.id = newID;
+			this.columnCount = columnCount;
+			this.store = createFileStore(id);
+			this.store.setCleanupReference(this);
+			this.lobIndexes = lobIndexes;
+		}
+		
+		public FileStore createStorage(String prefix) {
+			return createFileStore(id+prefix);
+		}
+
+		@Override
+		public ManagedBatch createManagedBatch(TupleBatch batch, boolean softCache)
+				throws TeiidComponentException {
+			ManagedBatchImpl mbi = new ManagedBatchImpl(batch, this, softCache);
+			mbi.addToCache(false);
+			persistBatchReferences();
+			return mbi;
+		}
+		
+		private boolean shouldCompact(long offset) {
+			return offset > COMPACTION_THRESHOLD && unusedSpace.get() * 4 > offset * 3;
+		}
+		
+		private long getOffset() throws TeiidComponentException {
+			long offset = store.getLength();
+			if (!shouldCompact(offset)) {
+				return offset;
+			}
+			try {
+				this.compactionLock.writeLock().lock();
+				offset = store.getLength();
+				//retest the condition to ensure that compaction is still needed
+				if (!shouldCompact(offset)) {
+					return offset;
+				}
+				FileStore newStore = createFileStore(id);
+				newStore.setCleanupReference(this);
+				byte[] buffer = new byte[IO_BUFFER_SIZE];
+				List<long[]> values = new ArrayList<long[]>(physicalMapping.values());
+				Collections.sort(values, new Comparator<long[]>() {
+					@Override
+					public int compare(long[] o1, long[] o2) {
+						return Long.signum(o1[0] - o2[0]);
+					}
+				});
+				for (long[] info : values) {
+					long oldOffset = info[0];
+					info[0] = newStore.getLength();
+					int size = (int)info[1];
+					while (size > 0) {
+						int toWrite = Math.min(IO_BUFFER_SIZE, size);
+						store.readFully(oldOffset, buffer, 0, toWrite);
+						newStore.write(buffer, 0, toWrite);
+						size -= toWrite;
+					}
+				}
+				store.remove();
+				store = newStore;
+				long oldOffset = offset;
+				offset = store.getLength();
+				LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, "Compacted store", id, "pre-size", oldOffset, "post-size", offset); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+				return offset;
+			} finally {
+				this.compactionLock.writeLock().unlock();
+			}
+		}
+
+		@Override
+		public void remove() {
+			this.store.remove();
+		}
+	}
+
+	/**
+	 * Holder for active batches
+	 */
+	private class TupleBufferInfo {
+		TreeMap<Integer, ManagedBatchImpl> batches = new TreeMap<Integer, ManagedBatchImpl>();
+		Integer lastUsed = null;
+		
+		ManagedBatchImpl removeBatch(int row) {
+			ManagedBatchImpl result = batches.remove(row);
+			if (result != null) {
+				activeBatchColumnCount -= result.batchManager.columnCount;
+			}
+			return result;
+		}
+	}
+	
+	private final class ManagedBatchImpl implements ManagedBatch {
+		private boolean persistent;
+		private boolean softCache;
+		private volatile TupleBatch activeBatch;
+		private volatile Reference<TupleBatch> batchReference;
+		private int beginRow;
+		private BatchManagerImpl batchManager;
+		private long id;
+		private LobManager lobManager;
+		
+		public ManagedBatchImpl(TupleBatch batch, BatchManagerImpl manager, boolean softCache) {
+			this.softCache = softCache;
+			id = batchAdded.incrementAndGet();
+            LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, "Add batch to BufferManager", id); //$NON-NLS-1$
+			this.activeBatch = batch;
+			this.beginRow = batch.getBeginRow();
+			this.batchManager = manager;
+			if (this.batchManager.lobIndexes != null) {
+				this.lobManager = new LobManager();
+			}
+		}
+
+		private void addToCache(boolean update) {
+			synchronized (activeBatches) {
+				TupleBatch batch = this.activeBatch;
+				if (batch == null) {
+					return; //already removed
+				}
+				activeBatchColumnCount += batchManager.columnCount;
+				TupleBufferInfo tbi = null;
+				if (update) {
+					tbi = activeBatches.remove(batchManager.id);
+				} else {
+					tbi = activeBatches.get(batchManager.id);
+				}
+				if (tbi == null) {
+					tbi = new TupleBufferInfo();
+					update = true;
+				} 
+				if (update) {
+					activeBatches.put(batchManager.id, tbi);
+				}
+				Assertion.isNull(tbi.batches.put(this.beginRow, this));
+			}
+		}
+
+		@Override
+		public TupleBatch getBatch(boolean cache, String[] types) throws TeiidComponentException {
+			long reads = readAttempts.incrementAndGet();
+			LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, batchManager.id, "getting batch", reads, "reference hits", referenceHit.get()); //$NON-NLS-1$ //$NON-NLS-2$
+			synchronized (activeBatches) {
+				TupleBufferInfo tbi = activeBatches.remove(batchManager.id);
+				if (tbi != null) { 
+					boolean put = true;
+					if (!cache) {
+						tbi.removeBatch(this.beginRow);
+						if (tbi.batches.isEmpty()) {
+							put = false;
+						}
+					}
+					if (put) {
+						tbi.lastUsed = this.beginRow;
+						activeBatches.put(batchManager.id, tbi);
+					}
+				}
+			}
+			persistBatchReferences();
+			synchronized (this) {
+				TupleBatch batch = this.activeBatch;
+				if (batch != null){
+					return batch;
+				}
+				Reference<TupleBatch> ref = this.batchReference;
+				this.batchReference = null;
+				if (ref != null) {
+					batch = ref.get();
+					if (batch != null) {
+						if (cache) {
+							this.activeBatch = batch;
+				        	addToCache(true);
+						} 
+						referenceHit.getAndIncrement();
+						return batch;
+					}
+				}
+				long count = readCount.incrementAndGet();
+				LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, batchManager.id, id, "reading batch from disk, total reads:", count); //$NON-NLS-1$
+				try {
+					this.batchManager.compactionLock.readLock().lock();
+					long[] info = batchManager.physicalMapping.get(this.id);
+					ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(batchManager.store.createInputStream(info[0]), IO_BUFFER_SIZE));
+		            batch = new TupleBatch();
+		            batch.setDataTypes(types);
+		            batch.readExternal(ois);
+		            batch.setRowOffset(this.beginRow);
+			        batch.setDataTypes(null);
+					if (lobManager != null) {
+						for (List<?> tuple : batch.getTuples()) {
+							lobManager.updateReferences(batchManager.lobIndexes, tuple);
+						}
+					}
+			        if (cache) {
+			        	this.activeBatch = batch;
+			        	addToCache(true);
+			        }
+					return batch;
+		        } catch(IOException e) {
+		        	throw new TeiidComponentException(e, QueryPlugin.Util.getString("FileStoreageManager.error_reading", batchManager.id)); //$NON-NLS-1$
+		        } catch (ClassNotFoundException e) {
+		        	throw new TeiidComponentException(e, QueryPlugin.Util.getString("FileStoreageManager.error_reading", batchManager.id)); //$NON-NLS-1$
+		        } finally {
+		        	this.batchManager.compactionLock.readLock().unlock();
+		        }
+			}
+		}
+
+		public synchronized void persist() throws TeiidComponentException {
+			boolean lockheld = false;
+            try {
+				TupleBatch batch = activeBatch;
+				if (batch != null) {
+					if (!persistent) {
+						long count = writeCount.incrementAndGet();
+						LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, batchManager.id, id, "writing batch to disk, total writes: ", count); //$NON-NLS-1$
+						long offset = 0;
+						if (lobManager != null) {
+							for (List<?> tuple : batch.getTuples()) {
+								lobManager.updateReferences(batchManager.lobIndexes, tuple);
+							}
+						}
+						synchronized (batchManager.store) {
+							offset = batchManager.getOffset();
+							OutputStream fsos = new BufferedOutputStream(batchManager.store.createOutputStream(), IO_BUFFER_SIZE);
+				            ObjectOutputStream oos = new ObjectOutputStream(fsos);
+				            batch.writeExternal(oos);
+				            oos.close();
+				            long size = batchManager.store.getLength() - offset;
+				            long[] info = new long[] {offset, size};
+				            batchManager.physicalMapping.put(this.id, info);
+						}
+						LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, batchManager.id, id, "batch written starting at:", offset); //$NON-NLS-1$
+					}
+					if (softCache) {
+						this.batchReference = new SoftReference<TupleBatch>(batch);
+					} else {
+						this.batchReference = new WeakReference<TupleBatch>(batch);
+					}
+				}
+			} catch (IOException e) {
+				throw new TeiidComponentException(e);
+			} catch (Throwable e) {
+				throw new TeiidComponentException(e);
+			} finally {
+				persistent = true;
+				activeBatch = null;
+				if (lockheld) {
+					this.batchManager.compactionLock.writeLock().unlock();
+				}
+			}
+		}
+
+		public void remove() {
+			synchronized (activeBatches) {
+				TupleBufferInfo tbi = activeBatches.get(batchManager.id);
+				if (tbi != null && tbi.removeBatch(this.beginRow) != null) {
+					if (tbi.batches.isEmpty()) {
+						activeBatches.remove(batchManager.id);
+					}
+				}
+			}
+			long[] info = batchManager.physicalMapping.remove(id);
+			if (info != null) {
+				batchManager.unusedSpace.addAndGet(info[1]); 
+			}
+			activeBatch = null;
+			batchReference = null;
+		}
+		
+		@Override
+		public String toString() {
+			return "ManagedBatch " + batchManager.id + " " + activeBatch; //$NON-NLS-1$ //$NON-NLS-2$
+		}
+	}
+	
+	// Configuration 
+    private int connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
+    private int processorBatchSize = BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE;
+    private int maxProcessingBatches = BufferManager.DEFAULT_MAX_PROCESSING_BATCHES;
+    private int maxReserveBatchColumns = BufferManager.DEFAULT_RESERVE_BUFFERS;
+    private volatile int reserveBatchColumns = BufferManager.DEFAULT_RESERVE_BUFFERS;
+    
+    private ReentrantLock lock = new ReentrantLock(true);
+    private Condition batchesFreed = lock.newCondition();
+    
+    private volatile int activeBatchColumnCount = 0;
+    private Map<String, TupleBufferInfo> activeBatches = new LinkedHashMap<String, TupleBufferInfo>();
+	private Map<String, TupleReference> tupleBufferMap = new ConcurrentHashMap<String, TupleReference>();
+	private ReferenceQueue<TupleBuffer> tupleBufferQueue = new ReferenceQueue<TupleBuffer>();
+    
+    
+    private StorageManager diskMgr;
+
+    private AtomicLong tsId = new AtomicLong();
+    private AtomicLong batchAdded = new AtomicLong();
+    private AtomicLong readCount = new AtomicLong();
+	private AtomicLong writeCount = new AtomicLong();
+	private AtomicLong readAttempts = new AtomicLong();
+	private AtomicLong referenceHit = new AtomicLong();
+	
+	public long getBatchesAdded() {
+		return batchAdded.get();
+	}
+	
+	public long getReadCount() {
+		return readCount.get();
+	}
+	
+	public long getWriteCount() {
+		return writeCount.get();
+	}
+	
+	public long getReadAttempts() {
+		return readAttempts.get();
+	}
+	
+	@Override
+    public int getMaxProcessingBatchColumns() {
+		return maxProcessingBatches;
+	}
+    
+    public void setMaxProcessingBatchColumns(int maxProcessingBatches) {
+		this.maxProcessingBatches = Math.max(0, maxProcessingBatches);
+	}
+
+    /**
+     * Get processor batch size
+     * @return Number of rows in a processor batch
+     */
+    @Override
+    public int getProcessorBatchSize() {        
+        return this.processorBatchSize;
+    }
+
+    /**
+     * Get connector batch size
+     * @return Number of rows in a connector batch
+     */
+    @Override
+    public int getConnectorBatchSize() {
+        return this.connectorBatchSize;
+    }
+    
+    public void setConnectorBatchSize(int connectorBatchSize) {
+        this.connectorBatchSize = connectorBatchSize;
+    } 
+
+    public void setProcessorBatchSize(int processorBatchSize) {
+        this.processorBatchSize = processorBatchSize;
+    } 
+
+    /**
+     * Add a storage manager to this buffer manager, order is unimportant
+     * @param storageManager Storage manager to add
+     */
+    public void setStorageManager(StorageManager storageManager) {
+    	Assertion.isNotNull(storageManager);
+    	Assertion.isNull(diskMgr);
+        this.diskMgr = storageManager;
+    }
+    
+    public StorageManager getStorageManager() {
+		return diskMgr;
+	}
+    
+    @Override
+    public TupleBuffer createTupleBuffer(final List elements, String groupName,
+    		TupleSourceType tupleSourceType) {
+    	final String newID = String.valueOf(this.tsId.getAndIncrement());
+    	int[] lobIndexes = LobManager.getLobIndexes(elements);
+    	BatchManager batchManager = new BatchManagerImpl(newID, elements.size(), lobIndexes);
+        TupleBuffer tupleBuffer = new TupleBuffer(batchManager, newID, elements, lobIndexes, getProcessorBatchSize());
+        LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Creating TupleBuffer:", newID, "of type ", tupleSourceType); //$NON-NLS-1$ //$NON-NLS-2$
+        return tupleBuffer;
+    }
+    
+    public STree createSTree(final List elements, String groupName, int keyLength) {
+    	String newID = String.valueOf(this.tsId.getAndIncrement());
+    	int[] lobIndexes = LobManager.getLobIndexes(elements);
+    	BatchManager bm = new BatchManagerImpl(newID, elements.size(), lobIndexes);
+    	BatchManager keyManager = new BatchManagerImpl(String.valueOf(this.tsId.getAndIncrement()), keyLength, null);
+    	int[] compareIndexes = new int[keyLength];
+    	for (int i = 1; i < compareIndexes.length; i++) {
+			compareIndexes[i] = i;
+		}
+        LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Creating STree:", newID); //$NON-NLS-1$ 
+    	return new STree(keyManager, bm, new ListNestedSortComparator(compareIndexes), getProcessorBatchSize(), keyLength, TupleBuffer.getTypeNames(elements));
+    }
+
+    @Override
+    public FileStore createFileStore(String name) {
+        LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Creating FileStore:", name); //$NON-NLS-1$ 
+    	return this.diskMgr.createFileStore(name);
+    }
+    
+	@Override
+	public void initialize() throws TeiidComponentException {
+		
+	}
+	
+    @Override
+    public void releaseBuffers(int count) {
+    	if (count < 1) {
+    		return;
+    	}
+    	lock.lock();
+    	try {
+	    	this.reserveBatchColumns += count;
+	    	batchesFreed.signalAll();
+    	} finally {
+    		lock.unlock();
+    	}
+    }	
+    
+    @Override
+    public int reserveBuffers(int count, BufferReserveMode mode) {
+    	lock.lock();
+	    try {
+	    	if (mode == BufferReserveMode.WAIT) {
+		    	int waitCount = 0;
+		    	while (count - waitCount > this.reserveBatchColumns) {
+		    		try {
+						batchesFreed.await(100, TimeUnit.MILLISECONDS);
+					} catch (InterruptedException e) {
+						throw new TeiidRuntimeException(e);
+					}
+					waitCount++;
+		    	}	
+	    	}
+	    	if (this.reserveBatchColumns >= count || mode == BufferReserveMode.FORCE) {
+		    	this.reserveBatchColumns -= count;
+	    		return count;
+	    	}
+	    	int result = Math.max(0, this.reserveBatchColumns);
+	    	this.reserveBatchColumns -= result;
+	    	return result;
+	    } finally {
+    		lock.unlock();
+    		persistBatchReferences();
+    	}
+    }
+    
+	void persistBatchReferences() {
+		if (activeBatchColumnCount == 0 || activeBatchColumnCount <= reserveBatchColumns) {
+			int memoryCount = activeBatchColumnCount + maxReserveBatchColumns - reserveBatchColumns;
+			if (DataTypeManager.isValueCacheEnabled()) {
+				if (memoryCount < maxReserveBatchColumns / 8) {
+					DataTypeManager.setValueCacheEnabled(false);
+				}
+			} else if (memoryCount > maxReserveBatchColumns / 4) {
+				DataTypeManager.setValueCacheEnabled(true);
+			}
+			return;
+		}
+		while (true) {
+			ManagedBatchImpl mb = null;
+			synchronized (activeBatches) {
+				if (activeBatchColumnCount == 0 || activeBatchColumnCount * 5 < reserveBatchColumns * 4) {
+					break;
+				}
+				Iterator<TupleBufferInfo> iter = activeBatches.values().iterator();
+				TupleBufferInfo tbi = iter.next();
+				Map.Entry<Integer, ManagedBatchImpl> entry = null;
+				if (tbi.lastUsed != null) {
+					entry = tbi.batches.floorEntry(tbi.lastUsed - 1);
+				}
+				if (entry == null) {
+					entry = tbi.batches.lastEntry();
+				} 
+				tbi.removeBatch(entry.getKey());
+				if (tbi.batches.isEmpty()) {
+					iter.remove();
+				}
+				mb = entry.getValue();
+			}
+			try {
+				mb.persist();
+			} catch (TeiidComponentException e) {
+				LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, e, "Error persisting batch, attempts to read that batch later will result in an exception"); //$NON-NLS-1$
+			}
+		}
+	}
+	
+	@Override
+	public int getSchemaSize(List elements) {
+		return elements.size();
+	}
+	
+    public void setMaxReserveBatchColumns(int maxReserve) {
+    	this.maxReserveBatchColumns = maxReserve;
+		this.reserveBatchColumns = maxReserve;
+	}
+
+	public void shutdown() {
+	}
+
+	@Override
+	public void addTupleBuffer(TupleBuffer tb) {
+		cleanDefunctTupleBuffers();
+		this.tupleBufferMap.put(tb.getId(), new TupleReference(tb, this.tupleBufferQueue));
+	}
+	
+	@Override
+	public TupleBuffer getTupleBuffer(String id) {		
+		cleanDefunctTupleBuffers();
+		Reference<TupleBuffer> r = this.tupleBufferMap.get(id);
+		if (r != null) {
+			return r.get();
+		}
+		return null;
+	}
+	
+	private void cleanDefunctTupleBuffers() {
+		while (true) {
+			Reference r = this.tupleBufferQueue.poll();
+			if (r == null) {
+				break;
+			}
+			this.tupleBufferMap.remove(((TupleReference)r).id);
+		}
+	}
+	
+	static class TupleReference extends WeakReference<TupleBuffer>{
+		String id;
+		public TupleReference(TupleBuffer referent, ReferenceQueue<? super TupleBuffer> q) {
+			super(referent, q);
+			id = referent.getId();
+		}
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,856 +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;
-    
-    // Resources
-    private BufferManager bufferManager;
-    private ProcessorDataManager dataTierMgr;
-    private SessionAwareCache<PreparedPlan> prepPlanCache;
-    private SessionAwareCache<CachedResults> rsCache;
-    private TransactionService transactionService;
-    private BufferService bufferService;
-    
-    private DQPConfiguration config = new DQPConfiguration();
-    
-    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 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.config.getQueryThresholdInSecs());
-    }
-
-    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(), this.config.getMaxRowsFetchSize()));
-		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.config.getUseDataRoles(), this.prepPlanCache);
-		request.setResultSetCacheEnabled(this.rsCache != null);
-		request.setAllowCreateTemporaryTablesByDefault(this.config.isAllowCreateTemporaryTablesByDefault());
-        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, this.config.getMaxRowsFetchSize()) - 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){
-			LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("DQPCore.clearing_resultset_cache", vdbName, version)); //$NON-NLS-1$
-			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.config.getTimeSliceInMilli();
-	}	
-	
-	int getChunkSize() {
-		return chunkSize;
-	}
-	
-	public void start(DQPConfiguration config) {
-		this.config = config;
-        
-        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 this.config.isExceptionOnMaxSourceRows();
-	}
-	
-	public int getMaxSourceRows() {
-		return this.config.getMaxSourceRows();
-	}
-	
-	public void setCacheFactory(CacheFactory factory) {
-		this.cacheFactory = factory;
-	}
-	
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java (from rev 2802, trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.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;
+    
+    // Resources
+    private BufferManager bufferManager;
+    private ProcessorDataManager dataTierMgr;
+    private SessionAwareCache<PreparedPlan> prepPlanCache;
+    private SessionAwareCache<CachedResults> rsCache;
+    private TransactionService transactionService;
+    private BufferService bufferService;
+    
+    private DQPConfiguration config = new DQPConfiguration();
+    
+    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 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.config.getQueryThresholdInSecs());
+    }
+
+    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(), this.config.getMaxRowsFetchSize()));
+		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.config.getUseDataRoles(), this.prepPlanCache);
+		request.setResultSetCacheEnabled(this.rsCache != null);
+		request.setAllowCreateTemporaryTablesByDefault(this.config.isAllowCreateTemporaryTablesByDefault());
+        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, this.config.getMaxRowsFetchSize()) - 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 = this.clientState.remove(sessionId);
+        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){
+			LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("DQPCore.clearing_resultset_cache", vdbName, version)); //$NON-NLS-1$
+			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.config.getTimeSliceInMilli();
+	}	
+	
+	int getChunkSize() {
+		return chunkSize;
+	}
+	
+	public void start(DQPConfiguration config) {
+		this.config = config;
+        
+        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 this.config.isExceptionOnMaxSourceRows();
+	}
+	
+	public int getMaxSourceRows() {
+		return this.config.getMaxSourceRows();
+	}
+	
+	public void setCacheFactory(CacheFactory factory) {
+		this.cacheFactory = factory;
+	}
+	
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,753 +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.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-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();
-				}
-				
-				try {
-					if (cid != null && this.resultsBuffer.isLobs()) {
-						this.resultsBuffer.persistLobs();
-					}
-				} catch (TeiidComponentException e) {
-					LogManager.logDetail(LogConstants.CTX_DQP, QueryPlugin.Util.getString("failed_to_cache")); //$NON-NLS-1$
-				}
-				
-				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) {
-					super.flushBatchDirect(batch, add);
-					added = true;
-				}
-				if (batch.getTerminationFlag()) {
-					doneProducingBatches();
-				}
-				if (doneProducingBatches && cid != null) {
-			    	Determinism determinismLevel = processor.getContext().getDeterminismLevel();
-	            	CachedResults cr = new CachedResults();
-	            	cr.setCommand(originalCommand);
-	                cr.setAnalysisRecord(analysisRecord);
-	                cr.setResults(resultsBuffer);
-	                
-	                if (originalCommand.getCacheHint() != null && originalCommand.getCacheHint().getDeterminism() != null) {
-						determinismLevel = originalCommand.getCacheHint().getDeterminism();
-						LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",processor.getContext().getDeterminismLevel(), " to ", determinismLevel }); //$NON-NLS-1$ //$NON-NLS-2$
-					}		                
-	                
-	                if (determinismLevel.compareTo(Determinism.SESSION_DETERMINISTIC) <= 0) {
-	    				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.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java (from rev 2803, trunk/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,751 @@
+/*
+ * 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.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+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();
+				} else {
+					try {
+						this.resultsBuffer.persistLobs();
+					} catch (TeiidComponentException e) {
+						LogManager.logDetail(LogConstants.CTX_DQP, QueryPlugin.Util.getString("failed_to_cache")); //$NON-NLS-1$
+					}
+				}
+				
+				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) {
+					super.flushBatchDirect(batch, add);
+					added = true;
+				}
+				if (batch.getTerminationFlag()) {
+					doneProducingBatches();
+				}
+				if (doneProducingBatches && cid != null) {
+			    	Determinism determinismLevel = processor.getContext().getDeterminismLevel();
+	            	CachedResults cr = new CachedResults();
+	            	cr.setCommand(originalCommand);
+	                cr.setAnalysisRecord(analysisRecord);
+	                cr.setResults(resultsBuffer);
+	                
+	                if (originalCommand.getCacheHint() != null && originalCommand.getCacheHint().getDeterminism() != null) {
+						determinismLevel = originalCommand.getCacheHint().getDeterminism();
+						LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",processor.getContext().getDeterminismLevel(), " to ", determinismLevel }); //$NON-NLS-1$ //$NON-NLS-2$
+					}		                
+	                
+	                if (determinismLevel.compareTo(Determinism.SESSION_DETERMINISTIC) <= 0) {
+	    				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.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/TransactionServerImpl.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/TransactionServerImpl.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/TransactionServerImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,541 +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.HashMap;
-import java.util.IdentityHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-
-import javax.resource.NotSupportedException;
-import javax.resource.spi.XATerminator;
-import javax.resource.spi.work.WorkException;
-import javax.resource.spi.work.WorkManager;
-import javax.transaction.HeuristicMixedException;
-import javax.transaction.HeuristicRollbackException;
-import javax.transaction.InvalidTransactionException;
-import javax.transaction.RollbackException;
-import javax.transaction.SystemException;
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-import javax.transaction.xa.XAException;
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.Xid;
-
-import org.teiid.adminapi.AdminException;
-import org.teiid.adminapi.AdminProcessingException;
-import org.teiid.adminapi.impl.TransactionMetadata;
-import org.teiid.client.xa.XATransactionException;
-import org.teiid.client.xa.XidImpl;
-import org.teiid.core.util.Assertion;
-import org.teiid.dqp.internal.process.DQPCore.FutureWork;
-import org.teiid.dqp.service.TransactionContext;
-import org.teiid.dqp.service.TransactionService;
-import org.teiid.dqp.service.TransactionContext.Scope;
-import org.teiid.query.QueryPlugin;
-
-
-public class TransactionServerImpl implements TransactionService {
-
-    private static class TransactionMapping {
-
-        // (connection -> transaction for global and local)
-        private Map<String, TransactionContext> threadToTransactionContext = new HashMap<String, TransactionContext>();
-        // (MMXid -> global transactions keyed) 
-        private Map<Xid, TransactionContext> xidToTransactionContext = new HashMap<Xid, TransactionContext>();
-        
-        public synchronized TransactionContext getOrCreateTransactionContext(String threadId) {
-            TransactionContext tc = threadToTransactionContext.get(threadId);
-
-            if (tc == null) {
-                tc = new TransactionContext();
-                tc.setThreadId(threadId);
-                threadToTransactionContext.put(threadId, tc);
-            }
-
-            return tc;
-        }
-        
-        public synchronized TransactionContext getTransactionContext(String threadId) {
-            return threadToTransactionContext.get(threadId);
-        }
-
-        public synchronized TransactionContext getTransactionContext(XidImpl xid) {
-            return xidToTransactionContext.get(xid);
-        }
-        
-        public synchronized TransactionContext removeTransactionContext(String threadId) {
-            return threadToTransactionContext.remove(threadId);
-        }
-
-        public synchronized void removeTransactionContext(TransactionContext tc) {
-            if (tc.getXid() != null) {
-                this.xidToTransactionContext.remove(tc.getXid());
-            }
-            if (tc.getThreadId() != null) {
-                this.threadToTransactionContext.remove(tc.getThreadId());
-            }
-        }
-        
-        public synchronized void addTransactionContext(TransactionContext tc) {
-            if (tc.getXid() != null) {
-                this.xidToTransactionContext.put(tc.getXid(), tc);
-            }
-            if (tc.getThreadId() != null) {
-                this.threadToTransactionContext.put(tc.getThreadId(), tc);
-            }
-        }
-    }
-
-    private TransactionMapping transactions = new TransactionMapping();
-    
-    private XATerminator xaTerminator;
-    private TransactionManager transactionManager;
-    private WorkManager workManager;
-
-    public void setXaTerminator(XATerminator xaTerminator) {
-		this.xaTerminator = xaTerminator;
-	}
-    
-    public void setTransactionManager(TransactionManager transactionManager) {
-		this.transactionManager = transactionManager;
-	}
-    
-    public void setWorkManager(WorkManager workManager) {
-		this.workManager = workManager;
-	}
-
-    /**
-     * Global Transaction 
-     */
-	public int prepare(final String threadId, XidImpl xid, boolean singleTM) throws XATransactionException {
-        TransactionContext tc = checkXAState(threadId, xid, true, false);
-        if (!tc.getSuspendedBy().isEmpty()) {
-            throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.suspended_exist", xid)); //$NON-NLS-1$
-        }		
-        
-        // In the container this pass though
-        if (singleTM) {        	    	
-	    	return XAResource.XA_RDONLY;
-        }
-        
-        try {
-        	return this.xaTerminator.prepare(tc.getXid());
-        } catch (XAException e) {
-            throw new XATransactionException(e);
-        }
-    }
-    
-    /**
-     * Global Transaction 
-     */    
-    public void commit(final String threadId, XidImpl xid, boolean onePhase, boolean singleTM) throws XATransactionException {
-    	TransactionContext tc = checkXAState(threadId, xid, true, false);  
-    	try {
-        	if (singleTM || (onePhase && XAResource.XA_RDONLY == prepare(threadId, xid, singleTM))) {
-        		return; //nothing to do
-        	}
-        	//TODO: we have no way of knowing for sure if we can safely use the onephase optimization
-        	this.xaTerminator.commit(tc.getXid(), false); 
-    	} catch (XAException e) {
-            throw new XATransactionException(e);
-        } finally {
-    		this.transactions.removeTransactionContext(tc);
-    	}
-    }
-    
-    /**
-     * Global Transaction 
-     */
-    public void rollback(final String threadId, XidImpl xid, boolean singleTM) throws XATransactionException {
-    	TransactionContext tc = checkXAState(threadId, xid, true, false);  
-    	try {
-    		// In the case of single TM, the container directly roll backs the sources.
-        	if (!singleTM) {
-        		this.xaTerminator.rollback(tc.getXid());
-        	}
-    	} catch (XAException e) {
-            throw new XATransactionException(e);
-        } finally {
-    		this.transactions.removeTransactionContext(tc);
-    	}
-    }
-
-    /**
-     * Global Transaction 
-     */    
-    public Xid[] recover(int flag, boolean singleTM) throws XATransactionException {
-    	// In case of single TM, container knows this list.
-    	if (singleTM) {
-    		return new Xid[0];
-    	}
-    	
-    	try {
-			return this.xaTerminator.recover(flag);
-		} catch (XAException e) {
-			throw new XATransactionException(e);
-		}
-    }
-
-    /**
-     * Global Transaction 
-     */    
-    public void forget(final String threadId, XidImpl xid, boolean singleTM) throws XATransactionException {
-    	TransactionContext tc = checkXAState(threadId, xid, true, false); 
-        try {
-        	if (singleTM) {
-        		return;
-        	}
-            this.xaTerminator.forget(xid);
-        } catch (XAException err) {
-            throw new XATransactionException(err);
-        } finally {
-        	this.transactions.removeTransactionContext(tc);
-        }
-    }
-
-    /**
-     * Global Transaction 
-     */
-    public void start(final String threadId, final XidImpl xid, int flags, int timeout, boolean singleTM) throws XATransactionException {
-        
-        TransactionContext tc = null;
-
-        switch (flags) {
-            case XAResource.TMNOFLAGS: {
-                try {
-					checkXAState(threadId, xid, false, false);
-					tc = transactions.getOrCreateTransactionContext(threadId);
-					if (tc.getTransactionType() != TransactionContext.Scope.NONE) {
-					    throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
-					}
-					tc.setTransactionTimeout(timeout);
-					tc.setXid(xid);
-					tc.setTransactionType(TransactionContext.Scope.GLOBAL);
-					if (singleTM) {
-						tc.setTransaction(transactionManager.getTransaction());
-						assert tc.getTransaction() != null;
-					} else {
-						FutureWork<Transaction> work = new FutureWork<Transaction>(new Callable<Transaction>() {
-							@Override
-							public Transaction call() throws Exception {
-								return transactionManager.getTransaction();
-							}
-						}, 0);
-						workManager.doWork(work, WorkManager.INDEFINITE, tc, null);
-						tc.setTransaction(work.getResult().get());
-					}
-				} catch (NotSupportedException e) {
-					throw new XATransactionException(e, XAException.XAER_INVAL);
-				} catch (WorkException e) {
-					throw new XATransactionException(e, XAException.XAER_INVAL);
-				} catch (InterruptedException e) {
-					throw new XATransactionException(e, XAException.XAER_INVAL);
-				} catch (ExecutionException e) {
-					throw new XATransactionException(e, XAException.XAER_INVAL);
-				} catch (SystemException e) {
-					throw new XATransactionException(e, XAException.XAER_INVAL);
-				}
-                break;
-            }
-            case XAResource.TMJOIN:
-            case XAResource.TMRESUME: {
-                tc = checkXAState(threadId, xid, true, false);
-                TransactionContext threadContext = transactions.getOrCreateTransactionContext(threadId);
-                if (threadContext.getTransactionType() != TransactionContext.Scope.NONE) {
-                    throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
-                }
-                
-                if (flags == XAResource.TMRESUME && !tc.getSuspendedBy().remove(threadId)) {
-                    throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.resume_failed", new Object[] {xid, threadId})); //$NON-NLS-1$
-                }
-                break;
-            }
-            default:
-                throw new XATransactionException(XAException.XAER_INVAL, QueryPlugin.Util.getString("TransactionServer.unknown_flags")); //$NON-NLS-1$
-        }
-
-        tc.setThreadId(threadId);
-        transactions.addTransactionContext(tc);
-    }
-
-    /**
-     * Global Transaction 
-     */    
-    public void end(final String threadId, XidImpl xid, int flags, boolean singleTM) throws XATransactionException {
-        TransactionContext tc = checkXAState(threadId, xid, true, true);
-        try {
-            switch (flags) {
-                case XAResource.TMSUSPEND: {
-                    tc.getSuspendedBy().add(threadId);
-                    break;
-                }
-                case XAResource.TMSUCCESS: {
-                    //TODO: should close all statements
-                    break;
-                }
-                case XAResource.TMFAIL: {
-                	cancelTransactions(threadId, false);
-                    break;
-                }
-                default:
-                    throw new XATransactionException(XAException.XAER_INVAL, QueryPlugin.Util.getString("TransactionServer.unknown_flags")); //$NON-NLS-1$
-            }
-        } finally {
-            tc.setThreadId(null);
-            transactions.removeTransactionContext(threadId);
-        }
-    }
-
-    private TransactionContext checkXAState(final String threadId, final XidImpl xid, boolean transactionExpected, boolean threadBound) throws XATransactionException {
-        TransactionContext tc = transactions.getTransactionContext(xid);
-        
-        if (transactionExpected && tc == null) {
-            throw new XATransactionException(XAException.XAER_NOTA, QueryPlugin.Util.getString("TransactionServer.no_global_transaction", xid)); //$NON-NLS-1$
-        } else if (!transactionExpected) {
-            if (tc != null) {
-                throw new XATransactionException(XAException.XAER_DUPID, QueryPlugin.Util.getString("TransactionServer.existing_global_transaction", new Object[] {xid})); //$NON-NLS-1$
-            }
-            if (!threadBound) {
-                tc = transactions.getOrCreateTransactionContext(threadId);
-                if (tc.getTransactionType() != TransactionContext.Scope.NONE) {
-                    throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.existing_transaction", new Object[] {xid, threadId})); //$NON-NLS-1$
-                }
-            }
-            return null;
-        } 
-        
-        if (threadBound) {
-            if (!threadId.equals(tc.getThreadId())) {
-                throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.wrong_transaction", xid)); //$NON-NLS-1$
-            }
-        } else if (tc.getThreadId() != null) {
-            throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.concurrent_transaction", xid)); //$NON-NLS-1$
-        }
-        
-        return tc;
-    }
-
-    private TransactionContext checkLocalTransactionState(String threadId, boolean transactionExpected) 
-    	throws XATransactionException {
-
-        final TransactionContext tc = transactions.getOrCreateTransactionContext(threadId);
-
-        try {
-	        if (tc.getTransactionType() != TransactionContext.Scope.NONE) {
-	            if (tc.getTransactionType() != TransactionContext.Scope.LOCAL) {
-	                throw new InvalidTransactionException(QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
-	            }
-	            if (!transactionExpected) {
-	            	throw new InvalidTransactionException(QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
-	            }
-	            transactionManager.resume(tc.getTransaction());
-	        } else if (transactionExpected) {
-	        	throw new InvalidTransactionException(QueryPlugin.Util.getString("TransactionServer.no_transaction", threadId)); //$NON-NLS-1$
-	        }
-        } catch (InvalidTransactionException e) {
-        	throw new XATransactionException(e);
-		} catch (SystemException e) {
-        	throw new XATransactionException(e);
-		}
-        return tc;
-    }
-    
-    private void beginDirect(TransactionContext tc) throws XATransactionException {
-		try {
-			transactionManager.begin();
-			Transaction tx = transactionManager.suspend();
-			tc.setTransaction(tx);
-			tc.setCreationTime(System.currentTimeMillis());
-        } catch (javax.transaction.NotSupportedException err) {
-            throw new XATransactionException(err);
-        } catch (SystemException err) {
-            throw new XATransactionException(err);
-        }
-	}
-	
-	private void commitDirect(TransactionContext context)
-			throws XATransactionException {
-		try {
-			transactionManager.commit();
-		} catch (SecurityException e) {
-			throw new XATransactionException(e);
-		} catch (RollbackException e) {
-			throw new XATransactionException(e);
-		} catch (HeuristicMixedException e) {
-			throw new XATransactionException(e);
-		} catch (HeuristicRollbackException e) {
-			throw new XATransactionException(e);
-		} catch (SystemException e) {
-			throw new XATransactionException(e);
-		} finally {
-			transactions.removeTransactionContext(context);
-		}
-	}
-
-	private void rollbackDirect(TransactionContext tc)
-			throws XATransactionException {
-		try {
-    		this.transactionManager.rollback();
-		} catch (SecurityException e) {
-			throw new XATransactionException(e);
-		} catch (SystemException e) {
-			throw new XATransactionException(e);
-		} finally {
-            transactions.removeTransactionContext(tc);
-        }
-	}
-	
-	public void suspend(TransactionContext context) throws XATransactionException {
-		try {
-			this.transactionManager.suspend();
-		} catch (SystemException e) {
-			throw new XATransactionException(e);
-		}
-	}
-	
-	public void resume(TransactionContext context) throws XATransactionException {
-		try {
-			this.transactionManager.resume(context.getTransaction());
-		} catch (InvalidTransactionException e) {
-			throw new XATransactionException(e);
-		} catch (SystemException e) {
-			throw new XATransactionException(e);
-		}
-	}
-
-    /**
-     * Local Transaction 
-     */
-    public TransactionContext begin(String threadId) throws XATransactionException {
-        TransactionContext tc = checkLocalTransactionState(threadId, false);
-        beginDirect(tc);
-        tc.setTransactionType(TransactionContext.Scope.LOCAL);
-        return tc;
-    }
-
-    /**
-     * Local Transaction 
-     */    
-    public void commit(String threadId) throws XATransactionException {
-        TransactionContext tc = checkLocalTransactionState(threadId, true);
-        commitDirect(tc);
-    }
-
-    /**
-     * Local Transaction 
-     */    
-    public void rollback(String threadId) throws XATransactionException {
-        TransactionContext tc = checkLocalTransactionState(threadId, true);
-        rollbackDirect(tc);
-    }
-
-    public TransactionContext getOrCreateTransactionContext(String threadId) {
-        return transactions.getOrCreateTransactionContext(threadId);
-    }
-
-    /**
-     * Request level transaction
-     */
-    public TransactionContext begin(TransactionContext context) throws XATransactionException{
-        if (context.getTransactionType() != TransactionContext.Scope.NONE) {
-            throw new XATransactionException(QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
-        }
-        beginDirect(context);
-        context.setTransactionType(TransactionContext.Scope.REQUEST);
-        return context;
-    }
-
-    /**
-     * Request level transaction
-     */    
-    public TransactionContext commit(TransactionContext context) throws XATransactionException {
-        Assertion.assertTrue(context.getTransactionType() == TransactionContext.Scope.REQUEST);
-        commitDirect(context);
-        return context;
-    }
-
-    /**
-     * Request level transaction
-     */    
-    public TransactionContext rollback(TransactionContext context) throws XATransactionException {
-        Assertion.assertTrue(context.getTransactionType() == TransactionContext.Scope.REQUEST);
-        rollbackDirect(context);
-        return context;      
-    }
-
-    public void cancelTransactions(String threadId, boolean requestOnly) throws XATransactionException {
-        TransactionContext tc = transactions.getTransactionContext(threadId);
-        
-        if (tc == null || tc.getTransactionType() == TransactionContext.Scope.NONE 
-        		|| (requestOnly && tc.getTransactionType() != TransactionContext.Scope.REQUEST)) {
-            return;
-        }
-        
-        try {
-            tc.getTransaction().setRollbackOnly();
-		} catch (SystemException e) {
-			throw new XATransactionException(e);
-		}
-    }
-
-	@Override
-	public Collection<org.teiid.adminapi.Transaction> getTransactions() {
-		Set<TransactionContext> txnSet = Collections.newSetFromMap(new IdentityHashMap<TransactionContext, Boolean>());
-		synchronized (this.transactions) {
-			txnSet.addAll(this.transactions.threadToTransactionContext.values());
-			txnSet.addAll(this.transactions.xidToTransactionContext.values());
-		}
-		Collection<org.teiid.adminapi.Transaction> result = new ArrayList<org.teiid.adminapi.Transaction>(txnSet.size());
-		for (TransactionContext transactionContext : txnSet) {
-			if (transactionContext.getTransactionType() == Scope.NONE) {
-				continue;
-			}
-			TransactionMetadata txnImpl = new TransactionMetadata();
-			txnImpl.setAssociatedSession(Long.parseLong(transactionContext.getThreadId()));
-			txnImpl.setCreatedTime(transactionContext.getCreationTime());
-			txnImpl.setScope(transactionContext.getTransactionType().toString());
-			txnImpl.setId(transactionContext.getTransactionId());
-			result.add(txnImpl);
-		}
-		return result;
-	}
-	
-	@Override
-	public void terminateTransaction(String threadId) throws AdminException {
-		if (threadId == null) {
-			return;
-		}
-		try {
-			cancelTransactions(threadId, false);
-		} catch (XATransactionException e) {
-			throw new AdminProcessingException(e);
-		}
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/TransactionServerImpl.java (from rev 2802, trunk/engine/src/main/java/org/teiid/dqp/internal/process/TransactionServerImpl.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/TransactionServerImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/dqp/internal/process/TransactionServerImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,541 @@
+/*
+ * 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.HashMap;
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+
+import javax.resource.NotSupportedException;
+import javax.resource.spi.XATerminator;
+import javax.resource.spi.work.WorkException;
+import javax.resource.spi.work.WorkManager;
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.InvalidTransactionException;
+import javax.transaction.RollbackException;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+import javax.transaction.xa.XAException;
+import javax.transaction.xa.XAResource;
+import javax.transaction.xa.Xid;
+
+import org.teiid.adminapi.AdminException;
+import org.teiid.adminapi.AdminProcessingException;
+import org.teiid.adminapi.impl.TransactionMetadata;
+import org.teiid.client.xa.XATransactionException;
+import org.teiid.client.xa.XidImpl;
+import org.teiid.core.util.Assertion;
+import org.teiid.dqp.internal.process.DQPCore.FutureWork;
+import org.teiid.dqp.service.TransactionContext;
+import org.teiid.dqp.service.TransactionService;
+import org.teiid.dqp.service.TransactionContext.Scope;
+import org.teiid.query.QueryPlugin;
+
+
+public class TransactionServerImpl implements TransactionService {
+
+    private static class TransactionMapping {
+
+        // (connection -> transaction for global and local)
+        private Map<String, TransactionContext> threadToTransactionContext = new HashMap<String, TransactionContext>();
+        // (MMXid -> global transactions keyed) 
+        private Map<Xid, TransactionContext> xidToTransactionContext = new HashMap<Xid, TransactionContext>();
+        
+        public synchronized TransactionContext getOrCreateTransactionContext(String threadId) {
+            TransactionContext tc = threadToTransactionContext.get(threadId);
+
+            if (tc == null) {
+                tc = new TransactionContext();
+                tc.setThreadId(threadId);
+                threadToTransactionContext.put(threadId, tc);
+            }
+
+            return tc;
+        }
+        
+        public synchronized TransactionContext getTransactionContext(String threadId) {
+            return threadToTransactionContext.get(threadId);
+        }
+
+        public synchronized TransactionContext getTransactionContext(XidImpl xid) {
+            return xidToTransactionContext.get(xid);
+        }
+        
+        public synchronized TransactionContext removeTransactionContext(String threadId) {
+            return threadToTransactionContext.remove(threadId);
+        }
+
+        public synchronized void removeTransactionContext(TransactionContext tc) {
+            if (tc.getXid() != null) {
+                this.xidToTransactionContext.remove(tc.getXid());
+            }
+            if (tc.getThreadId() != null) {
+                this.threadToTransactionContext.remove(tc.getThreadId());
+            }
+        }
+        
+        public synchronized void addTransactionContext(TransactionContext tc) {
+            if (tc.getXid() != null) {
+                this.xidToTransactionContext.put(tc.getXid(), tc);
+            }
+            if (tc.getThreadId() != null) {
+                this.threadToTransactionContext.put(tc.getThreadId(), tc);
+            }
+        }
+    }
+
+    private TransactionMapping transactions = new TransactionMapping();
+    
+    private XATerminator xaTerminator;
+    private TransactionManager transactionManager;
+    private WorkManager workManager;
+
+    public void setXaTerminator(XATerminator xaTerminator) {
+		this.xaTerminator = xaTerminator;
+	}
+    
+    public void setTransactionManager(TransactionManager transactionManager) {
+		this.transactionManager = transactionManager;
+	}
+    
+    public void setWorkManager(WorkManager workManager) {
+		this.workManager = workManager;
+	}
+
+    /**
+     * Global Transaction 
+     */
+	public int prepare(final String threadId, XidImpl xid, boolean singleTM) throws XATransactionException {
+        TransactionContext tc = checkXAState(threadId, xid, true, false);
+        if (!tc.getSuspendedBy().isEmpty()) {
+            throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.suspended_exist", xid)); //$NON-NLS-1$
+        }		
+        
+        // In the container this pass though
+        if (singleTM) {        	    	
+	    	return XAResource.XA_RDONLY;
+        }
+        
+        try {
+        	return this.xaTerminator.prepare(tc.getXid());
+        } catch (XAException e) {
+            throw new XATransactionException(e);
+        }
+    }
+    
+    /**
+     * Global Transaction 
+     */    
+    public void commit(final String threadId, XidImpl xid, boolean onePhase, boolean singleTM) throws XATransactionException {
+    	TransactionContext tc = checkXAState(threadId, xid, true, false);  
+    	try {
+        	if (singleTM || (onePhase && XAResource.XA_RDONLY == prepare(threadId, xid, singleTM))) {
+        		return; //nothing to do
+        	}
+        	//TODO: we have no way of knowing for sure if we can safely use the onephase optimization
+        	this.xaTerminator.commit(tc.getXid(), false); 
+    	} catch (XAException e) {
+            throw new XATransactionException(e);
+        } finally {
+    		this.transactions.removeTransactionContext(tc);
+    	}
+    }
+    
+    /**
+     * Global Transaction 
+     */
+    public void rollback(final String threadId, XidImpl xid, boolean singleTM) throws XATransactionException {
+    	TransactionContext tc = checkXAState(threadId, xid, true, false);  
+    	try {
+    		// In the case of single TM, the container directly roll backs the sources.
+        	if (!singleTM) {
+        		this.xaTerminator.rollback(tc.getXid());
+        	}
+    	} catch (XAException e) {
+            throw new XATransactionException(e);
+        } finally {
+    		this.transactions.removeTransactionContext(tc);
+    	}
+    }
+
+    /**
+     * Global Transaction 
+     */    
+    public Xid[] recover(int flag, boolean singleTM) throws XATransactionException {
+    	// In case of single TM, container knows this list.
+    	if (singleTM) {
+    		return new Xid[0];
+    	}
+    	
+    	try {
+			return this.xaTerminator.recover(flag);
+		} catch (XAException e) {
+			throw new XATransactionException(e);
+		}
+    }
+
+    /**
+     * Global Transaction 
+     */    
+    public void forget(final String threadId, XidImpl xid, boolean singleTM) throws XATransactionException {
+    	TransactionContext tc = checkXAState(threadId, xid, true, false); 
+        try {
+        	if (singleTM) {
+        		return;
+        	}
+            this.xaTerminator.forget(xid);
+        } catch (XAException err) {
+            throw new XATransactionException(err);
+        } finally {
+        	this.transactions.removeTransactionContext(tc);
+        }
+    }
+
+    /**
+     * Global Transaction 
+     */
+    public void start(final String threadId, final XidImpl xid, int flags, int timeout, boolean singleTM) throws XATransactionException {
+        
+        TransactionContext tc = null;
+
+        switch (flags) {
+            case XAResource.TMNOFLAGS: {
+                try {
+					checkXAState(threadId, xid, false, false);
+					tc = transactions.getOrCreateTransactionContext(threadId);
+					if (tc.getTransactionType() != TransactionContext.Scope.NONE) {
+					    throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
+					}
+					tc.setTransactionTimeout(timeout);
+					tc.setXid(xid);
+					tc.setTransactionType(TransactionContext.Scope.GLOBAL);
+					if (singleTM) {
+						tc.setTransaction(transactionManager.getTransaction());
+						assert tc.getTransaction() != null;
+					} else {
+						FutureWork<Transaction> work = new FutureWork<Transaction>(new Callable<Transaction>() {
+							@Override
+							public Transaction call() throws Exception {
+								return transactionManager.getTransaction();
+							}
+						}, 0);
+						workManager.doWork(work, WorkManager.INDEFINITE, tc, null);
+						tc.setTransaction(work.getResult().get());
+					}
+				} catch (NotSupportedException e) {
+					throw new XATransactionException(e, XAException.XAER_INVAL);
+				} catch (WorkException e) {
+					throw new XATransactionException(e, XAException.XAER_INVAL);
+				} catch (InterruptedException e) {
+					throw new XATransactionException(e, XAException.XAER_INVAL);
+				} catch (ExecutionException e) {
+					throw new XATransactionException(e, XAException.XAER_INVAL);
+				} catch (SystemException e) {
+					throw new XATransactionException(e, XAException.XAER_INVAL);
+				}
+                break;
+            }
+            case XAResource.TMJOIN:
+            case XAResource.TMRESUME: {
+                tc = checkXAState(threadId, xid, true, false);
+                TransactionContext threadContext = transactions.getOrCreateTransactionContext(threadId);
+                if (threadContext.getTransactionType() != TransactionContext.Scope.NONE) {
+                    throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
+                }
+                
+                if (flags == XAResource.TMRESUME && !tc.getSuspendedBy().remove(threadId)) {
+                    throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.resume_failed", new Object[] {xid, threadId})); //$NON-NLS-1$
+                }
+                break;
+            }
+            default:
+                throw new XATransactionException(XAException.XAER_INVAL, QueryPlugin.Util.getString("TransactionServer.unknown_flags")); //$NON-NLS-1$
+        }
+
+        tc.setThreadId(threadId);
+        transactions.addTransactionContext(tc);
+    }
+
+    /**
+     * Global Transaction 
+     */    
+    public void end(final String threadId, XidImpl xid, int flags, boolean singleTM) throws XATransactionException {
+        TransactionContext tc = checkXAState(threadId, xid, true, true);
+        try {
+            switch (flags) {
+                case XAResource.TMSUSPEND: {
+                    tc.getSuspendedBy().add(threadId);
+                    break;
+                }
+                case XAResource.TMSUCCESS: {
+                    //TODO: should close all statements
+                    break;
+                }
+                case XAResource.TMFAIL: {
+                	cancelTransactions(threadId, false);
+                    break;
+                }
+                default:
+                    throw new XATransactionException(XAException.XAER_INVAL, QueryPlugin.Util.getString("TransactionServer.unknown_flags")); //$NON-NLS-1$
+            }
+        } finally {
+            tc.setThreadId(null);
+            transactions.removeTransactionContext(threadId);
+        }
+    }
+
+    private TransactionContext checkXAState(final String threadId, final XidImpl xid, boolean transactionExpected, boolean threadBound) throws XATransactionException {
+        TransactionContext tc = transactions.getTransactionContext(xid);
+        
+        if (transactionExpected && tc == null) {
+            throw new XATransactionException(XAException.XAER_NOTA, QueryPlugin.Util.getString("TransactionServer.no_global_transaction", xid)); //$NON-NLS-1$
+        } else if (!transactionExpected) {
+            if (tc != null) {
+                throw new XATransactionException(XAException.XAER_DUPID, QueryPlugin.Util.getString("TransactionServer.existing_global_transaction", new Object[] {xid})); //$NON-NLS-1$
+            }
+            if (!threadBound) {
+                tc = transactions.getOrCreateTransactionContext(threadId);
+                if (tc.getTransactionType() != TransactionContext.Scope.NONE) {
+                    throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.existing_transaction", new Object[] {xid, threadId})); //$NON-NLS-1$
+                }
+            }
+            return null;
+        } 
+        
+        if (threadBound) {
+            if (!threadId.equals(tc.getThreadId())) {
+                throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.wrong_transaction", xid)); //$NON-NLS-1$
+            }
+        } else if (tc.getThreadId() != null) {
+            throw new XATransactionException(XAException.XAER_PROTO, QueryPlugin.Util.getString("TransactionServer.concurrent_transaction", xid)); //$NON-NLS-1$
+        }
+        
+        return tc;
+    }
+
+    private TransactionContext checkLocalTransactionState(String threadId, boolean transactionExpected) 
+    	throws XATransactionException {
+
+        final TransactionContext tc = transactions.getOrCreateTransactionContext(threadId);
+
+        try {
+	        if (tc.getTransactionType() != TransactionContext.Scope.NONE) {
+	            if (tc.getTransactionType() != TransactionContext.Scope.LOCAL) {
+	                throw new InvalidTransactionException(QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
+	            }
+	            if (!transactionExpected) {
+	            	throw new InvalidTransactionException(QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
+	            }
+	            transactionManager.resume(tc.getTransaction());
+	        } else if (transactionExpected) {
+	        	throw new InvalidTransactionException(QueryPlugin.Util.getString("TransactionServer.no_transaction", threadId)); //$NON-NLS-1$
+	        }
+        } catch (InvalidTransactionException e) {
+        	throw new XATransactionException(e);
+		} catch (SystemException e) {
+        	throw new XATransactionException(e);
+		}
+        return tc;
+    }
+    
+    private void beginDirect(TransactionContext tc) throws XATransactionException {
+		try {
+			transactionManager.begin();
+			Transaction tx = transactionManager.suspend();
+			tc.setTransaction(tx);
+			tc.setCreationTime(System.currentTimeMillis());
+        } catch (javax.transaction.NotSupportedException err) {
+            throw new XATransactionException(err);
+        } catch (SystemException err) {
+            throw new XATransactionException(err);
+        }
+	}
+	
+	private void commitDirect(TransactionContext context)
+			throws XATransactionException {
+		try {
+			transactionManager.commit();
+		} catch (SecurityException e) {
+			throw new XATransactionException(e);
+		} catch (RollbackException e) {
+			throw new XATransactionException(e);
+		} catch (HeuristicMixedException e) {
+			throw new XATransactionException(e);
+		} catch (HeuristicRollbackException e) {
+			throw new XATransactionException(e);
+		} catch (SystemException e) {
+			throw new XATransactionException(e);
+		} finally {
+			transactions.removeTransactionContext(context);
+		}
+	}
+
+	private void rollbackDirect(TransactionContext tc)
+			throws XATransactionException {
+		try {
+    		this.transactionManager.rollback();
+		} catch (SecurityException e) {
+			throw new XATransactionException(e);
+		} catch (SystemException e) {
+			throw new XATransactionException(e);
+		} finally {
+            transactions.removeTransactionContext(tc);
+        }
+	}
+	
+	public void suspend(TransactionContext context) throws XATransactionException {
+		try {
+			this.transactionManager.suspend();
+		} catch (SystemException e) {
+			throw new XATransactionException(e);
+		}
+	}
+	
+	public void resume(TransactionContext context) throws XATransactionException {
+		try {
+			this.transactionManager.resume(context.getTransaction());
+		} catch (InvalidTransactionException e) {
+			throw new XATransactionException(e);
+		} catch (SystemException e) {
+			throw new XATransactionException(e);
+		}
+	}
+
+    /**
+     * Local Transaction 
+     */
+    public TransactionContext begin(String threadId) throws XATransactionException {
+        TransactionContext tc = checkLocalTransactionState(threadId, false);
+        beginDirect(tc);
+        tc.setTransactionType(TransactionContext.Scope.LOCAL);
+        return tc;
+    }
+
+    /**
+     * Local Transaction 
+     */    
+    public void commit(String threadId) throws XATransactionException {
+        TransactionContext tc = checkLocalTransactionState(threadId, true);
+        commitDirect(tc);
+    }
+
+    /**
+     * Local Transaction 
+     */    
+    public void rollback(String threadId) throws XATransactionException {
+        TransactionContext tc = checkLocalTransactionState(threadId, true);
+        rollbackDirect(tc);
+    }
+
+    public TransactionContext getOrCreateTransactionContext(String threadId) {
+        return transactions.getOrCreateTransactionContext(threadId);
+    }
+
+    /**
+     * Request level transaction
+     */
+    public TransactionContext begin(TransactionContext context) throws XATransactionException{
+        if (context.getTransactionType() != TransactionContext.Scope.NONE) {
+            throw new XATransactionException(QueryPlugin.Util.getString("TransactionServer.existing_transaction")); //$NON-NLS-1$
+        }
+        beginDirect(context);
+        context.setTransactionType(TransactionContext.Scope.REQUEST);
+        return context;
+    }
+
+    /**
+     * Request level transaction
+     */    
+    public TransactionContext commit(TransactionContext context) throws XATransactionException {
+        Assertion.assertTrue(context.getTransactionType() == TransactionContext.Scope.REQUEST);
+        commitDirect(context);
+        return context;
+    }
+
+    /**
+     * Request level transaction
+     */    
+    public TransactionContext rollback(TransactionContext context) throws XATransactionException {
+        Assertion.assertTrue(context.getTransactionType() == TransactionContext.Scope.REQUEST);
+        rollbackDirect(context);
+        return context;      
+    }
+
+    public void cancelTransactions(String threadId, boolean requestOnly) throws XATransactionException {
+    	TransactionContext tc = requestOnly?transactions.getTransactionContext(threadId):transactions.removeTransactionContext(threadId);
+        
+        if (tc == null || tc.getTransactionType() == TransactionContext.Scope.NONE 
+        		|| (requestOnly && tc.getTransactionType() != TransactionContext.Scope.REQUEST)) {
+            return;
+        }
+        
+        try {
+            tc.getTransaction().setRollbackOnly();
+		} catch (SystemException e) {
+			throw new XATransactionException(e);
+		}
+    }
+
+	@Override
+	public Collection<org.teiid.adminapi.Transaction> getTransactions() {
+		Set<TransactionContext> txnSet = Collections.newSetFromMap(new IdentityHashMap<TransactionContext, Boolean>());
+		synchronized (this.transactions) {
+			txnSet.addAll(this.transactions.threadToTransactionContext.values());
+			txnSet.addAll(this.transactions.xidToTransactionContext.values());
+		}
+		Collection<org.teiid.adminapi.Transaction> result = new ArrayList<org.teiid.adminapi.Transaction>(txnSet.size());
+		for (TransactionContext transactionContext : txnSet) {
+			if (transactionContext.getTransactionType() == Scope.NONE) {
+				continue;
+			}
+			TransactionMetadata txnImpl = new TransactionMetadata();
+			txnImpl.setAssociatedSession(Long.parseLong(transactionContext.getThreadId()));
+			txnImpl.setCreatedTime(transactionContext.getCreationTime());
+			txnImpl.setScope(transactionContext.getTransactionType().toString());
+			txnImpl.setId(transactionContext.getTransactionId());
+			result.add(txnImpl);
+		}
+		return result;
+	}
+	
+	@Override
+	public void terminateTransaction(String threadId) throws AdminException {
+		if (threadId == null) {
+			return;
+		}
+		try {
+			cancelTransactions(threadId, false);
+		} catch (XATransactionException e) {
+			throw new AdminProcessingException(e);
+		}
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,1224 +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;
-
-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.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryParserException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.client.plan.Annotation;
-import org.teiid.client.plan.Annotation.Priority;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.id.IDGenerator;
-import org.teiid.dqp.internal.process.Request;
-import org.teiid.language.SQLConstants;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.TriggerActionPlanner;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-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.optimizer.relational.plantree.NodeConstants.Info;
-import org.teiid.query.optimizer.relational.rules.CapabilitiesUtil;
-import org.teiid.query.optimizer.relational.rules.CriteriaCapabilityValidatorVisitor;
-import org.teiid.query.optimizer.relational.rules.RuleCollapseSource;
-import org.teiid.query.optimizer.relational.rules.RuleConstants;
-import org.teiid.query.optimizer.relational.rules.RuleMergeCriteria;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
-import org.teiid.query.resolver.ProcedureContainerResolver;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.resolver.util.BindVariableVisitor;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.LanguageObject.Util;
-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.lang.Delete;
-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.JoinPredicate;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.Limit;
-import org.teiid.query.sql.lang.Option;
-import org.teiid.query.sql.lang.OrderBy;
-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.Select;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.TableFunctionReference;
-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.navigator.PreOrPostOrderNavigator;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-import org.teiid.query.sql.proc.TriggerAction;
-import org.teiid.query.sql.symbol.AllSymbol;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.SelectSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
-import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
-import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.validator.ValidationVisitor;
-import org.teiid.query.validator.UpdateValidator.UpdateInfo;
-
-
-/**
- * This class generates a relational plan for query execution.  The output of
- * this class is a {@link org.teiid.query.optimizer.relational.plantree.PlanNode PlanNode}
- * object - this object then becomes the input to
- * {@link PlanToProcessConverter PlanToProcessConverter}
- * to  produce a
- * {@link org.teiid.query.processor.relational.RelationalPlan RelationalPlan}.
- */
-public class RelationalPlanner {
-	
-	public static final String MAT_PREFIX = "#MAT_"; //$NON-NLS-1$
-	
-	private AnalysisRecord analysisRecord;
-	private Command parentCommand;
-	private IDGenerator idGenerator;
-	private CommandContext context;
-	private CapabilitiesFinder capFinder;
-	private QueryMetadataInterface metadata;
-	private PlanHints hints = new PlanHints();
-	private Option option;
-	
-    public ProcessorPlan optimize(
-        Command command)
-        throws
-            QueryPlannerException,
-            QueryMetadataException,
-            TeiidComponentException {
-
-        boolean debug = analysisRecord.recordDebug();
-		if(debug) {
-            analysisRecord.println("\n----------------------------------------------------------------------------"); //$NON-NLS-1$
-            analysisRecord.println("GENERATE CANONICAL: \n" + command); //$NON-NLS-1$
-		}   
-		
-		PlanToProcessConverter planToProcessConverter = null;
-        if (context != null) {
-        	planToProcessConverter = context.getPlanToProcessConverter();
-        }
-        if (planToProcessConverter == null) {
-        	planToProcessConverter = new PlanToProcessConverter(metadata, idGenerator, analysisRecord, capFinder);
-        }
-		
-		//plan with
-        List<WithQueryCommand> withList = null;
-        Object modelID = null;
-		boolean supportsWithPushdown = true;
-		List<WithQueryCommand> pushDownWith = null;
-		if (command instanceof QueryCommand) {
-			QueryCommand queryCommand = (QueryCommand)command;
-			final HashSet<String> names = new HashSet<String>();
-			if (queryCommand.getWith() != null) {
-	        	withList = queryCommand.getWith();
-	        	for (WithQueryCommand with : queryCommand.getWith()) {
-	        		Command subCommand = with.getCommand();
-	                ProcessorPlan procPlan = QueryOptimizer.optimizePlan(subCommand, metadata, idGenerator, capFinder, analysisRecord, context);
-	                subCommand.setProcessorPlan(procPlan);
-	                QueryCommand withCommand = CriteriaCapabilityValidatorVisitor.getQueryCommand(procPlan);
-	                if (withCommand != null && supportsWithPushdown) {
-	                	modelID = CriteriaCapabilityValidatorVisitor.validateCommandPushdown(modelID, metadata, capFinder, withCommand);
-	            	}
-	                if (modelID == null) {
-	                	supportsWithPushdown = false;
-	                } else {
-	                	if (pushDownWith == null) {
-	                		pushDownWith = new ArrayList<WithQueryCommand>();
-	                	}
-	                	WithQueryCommand wqc = new WithQueryCommand(with.getGroupSymbol(), with.getColumns(), withCommand);
-	                	pushDownWith.add(wqc);
-	                }
-		        	names.add(with.getGroupSymbol().getCanonicalName());
-				}
-	        	if (modelID != null && supportsWithPushdown) {
-	        		supportsWithPushdown = CapabilitiesUtil.supports(Capability.COMMON_TABLE_EXPRESSIONS, modelID, metadata, capFinder);
-	        	}
-				if (supportsWithPushdown) {
-					addModelIds(command, modelID, names);
-				}
-	        }
-		}
-				
-        PlanNode plan;
-		try {
-			plan = generatePlan(command);
-		} catch (TeiidProcessingException e) {
-			throw new QueryPlannerException(e, e.getMessage());
-		}
-
-		if(debug) {
-            analysisRecord.println("\nCANONICAL PLAN: \n" + plan); //$NON-NLS-1$
-		} 
-
-        // Connect ProcessorPlan to SubqueryContainer (if any) of SELECT or PROJECT nodes
-		connectSubqueryContainers(plan); //TODO: merge with node creation
-        
-        // Set top column information on top node
-        List<SingleElementSymbol> topCols = Util.deepClone(command.getProjectedSymbols(), SingleElementSymbol.class);
-
-        // Build rule set based on hints
-        RuleStack rules = buildRules();
-
-        // Run rule-based optimizer
-        plan = executeRules(rules, plan);
-
-        RelationalPlan result = planToProcessConverter.convert(plan);
-        if (withList != null && supportsWithPushdown) {
-        	QueryCommand queryCommand = CriteriaCapabilityValidatorVisitor.getQueryCommand(result);
-        	if (queryCommand != null) { 
-				if (CriteriaCapabilityValidatorVisitor.validateCommandPushdown(modelID, metadata, capFinder, queryCommand) == null) {
-					supportsWithPushdown = false;
-				} else {
-					queryCommand.setWith(pushDownWith);
-				}
-        	} else {
-        		supportsWithPushdown = false;
-        	}
-        }
-        if (!supportsWithPushdown) {
-        	result.setWith(withList);
-        }
-        result.setOutputElements(topCols);
-        
-        return result;
-    }
-
-    /**
-     * mark all relevant group symbols as being from the modelid
-     * @param command
-     * @param modelID
-     * @param names
-     */
-	private void addModelIds(Command command, final Object modelID,
-			final HashSet<String> names) {
-		PreOrPostOrderNavigator.doVisit(command, new LanguageVisitor() {
-			@Override
-			public void visit(UnaryFromClause obj) {
-				GroupSymbol group = obj.getGroup();
-				if (names.contains(group.getNonCorrelationName().toUpperCase())) {
-					group.setModelMetadataId(modelID);
-				}
-			}
-		}, PreOrPostOrderNavigator.POST_ORDER, true);  
-	}
-
-	public void initialize(Command command, IDGenerator idGenerator,
-			QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
-			AnalysisRecord analysisRecord, CommandContext context) {
-		this.parentCommand = command;
-    	this.idGenerator = idGenerator;
-    	this.metadata = metadata;
-    	this.capFinder = capFinder;
-    	this.analysisRecord = analysisRecord;
-    	this.context = context;
-	}
-
-    private void connectSubqueryContainers(PlanNode plan) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-        Set<GroupSymbol> groupSymbols = getGroupSymbols(plan);
-
-        for (PlanNode node : NodeEditor.findAllNodes(plan, NodeConstants.Types.PROJECT | NodeConstants.Types.SELECT | NodeConstants.Types.JOIN)) {
-            List<SubqueryContainer> subqueryContainers = node.getSubqueryContainers();
-            if (subqueryContainers.isEmpty()){
-            	continue;
-            }
-            Set<GroupSymbol> localGroupSymbols = groupSymbols;
-            if (node.getType() == NodeConstants.Types.JOIN) {
-            	localGroupSymbols = getGroupSymbols(node);
-            }
-            for (SubqueryContainer container : subqueryContainers) {
-                //a clone is needed here because the command could get modified during planning
-                Command subCommand = (Command)container.getCommand().clone(); 
-                ArrayList<Reference> correlatedReferences = new ArrayList<Reference>();
-                CorrelatedReferenceCollectorVisitor.collectReferences(subCommand, localGroupSymbols, correlatedReferences);
-                ProcessorPlan procPlan = QueryOptimizer.optimizePlan(subCommand, metadata, idGenerator, capFinder, analysisRecord, context);
-                container.getCommand().setProcessorPlan(procPlan);
-                if (!correlatedReferences.isEmpty()) {
-	                SymbolMap map = new SymbolMap();
-	                for (Reference reference : correlatedReferences) {
-	    				map.addMapping(reference.getExpression(), reference.getExpression());
-	    			}
-	                container.getCommand().setCorrelatedReferences(map);
-                }
-            }
-            node.addGroups(GroupsUsedByElementsVisitor.getGroups(node.getCorrelatedReferenceElements()));
-        }
-    }
-
-	private static Set<GroupSymbol> getGroupSymbols(PlanNode plan) {
-		Set<GroupSymbol> groupSymbols = new HashSet<GroupSymbol>();
-        for (PlanNode source : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE)) {
-            groupSymbols.addAll(source.getGroups());
-        }
-		return groupSymbols;
-	}
-
-    /**
-     * Distribute and "make (not) dependent" hints specified in the query into the
-     * fully resolved query plan.  This is done after virtual group resolution so
-     * that all groups in the plan are known.  The hint is attached to all SOURCE
-     * nodes for each group that should be made dependent/not dependent.
-     * @param groups List of groups (Strings) to be made dependent
-     * @param plan The canonical plan
-     */
-    private void distributeDependentHints(Collection<String> groups, PlanNode plan, NodeConstants.Info hintProperty)
-        throws QueryMetadataException, TeiidComponentException {
-    
-        if(groups == null || groups.isEmpty()) {
-        	return;
-        }
-        // Get all source nodes
-        List<PlanNode> nodes = NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE);
-
-        // Walk through each dependent group hint and
-        // attach to the correct source node
-        for (String groupName : groups) {
-            // Walk through nodes and apply hint to all that match group name
-            boolean appliedHint = applyHint(nodes, groupName, hintProperty);
-
-            if(! appliedHint) {
-                //check if it is partial group name
-                Collection groupNames = metadata.getGroupsForPartialName(groupName);
-                if(groupNames.size() == 1) {
-                    groupName = (String)groupNames.iterator().next();
-                    appliedHint = applyHint(nodes, groupName, hintProperty);
-                }
-                
-                if(! appliedHint) {
-                	String msg = QueryPlugin.Util.getString("ERR.015.004.0010", groupName); //$NON-NLS-1$
-                	if (this.analysisRecord.recordAnnotations()) {
-                		this.analysisRecord.addAnnotation(new Annotation(Annotation.HINTS, msg, "ignoring hint", Priority.MEDIUM)); //$NON-NLS-1$
-                	}
-                }
-            }
-        }
-    }
-    
-    private static boolean applyHint(List<PlanNode> nodes, String groupName, NodeConstants.Info hintProperty) {
-        boolean appliedHint = false;
-        for (PlanNode node : nodes) {
-            GroupSymbol nodeGroup = node.getGroups().iterator().next();
-            
-            String sDefinition = nodeGroup.getDefinition();
-            
-            if (nodeGroup.getName().equalsIgnoreCase(groupName) 
-             || (sDefinition != null && sDefinition.equalsIgnoreCase(groupName)) ) {
-                node.setProperty(hintProperty, Boolean.TRUE);
-                appliedHint = true;
-            }
-        }
-        return appliedHint;
-    }
-
-    public RuleStack buildRules() {
-        RuleStack rules = new RuleStack();
-
-        rules.push(RuleConstants.COLLAPSE_SOURCE);
-        
-        rules.push(RuleConstants.PLAN_SORTS);
-        
-        //TODO: update plan sorts to take advantage or semi-join ordering
-        if (hints.hasJoin || hints.hasCriteria) {
-            rules.push(new RuleMergeCriteria(idGenerator, capFinder, analysisRecord, context, metadata));
-        }
-
-        if(hints.hasJoin) {
-            rules.push(RuleConstants.IMPLEMENT_JOIN_STRATEGY);
-        }
-        
-        rules.push(RuleConstants.ASSIGN_OUTPUT_ELEMENTS);
-        
-        rules.push(RuleConstants.CALCULATE_COST);
-        
-        if (hints.hasLimit) {
-            rules.push(RuleConstants.PUSH_LIMIT);
-        }
-        if (hints.hasRelationalProc) {
-            rules.push(RuleConstants.PLAN_PROCEDURES);
-        }
-        if(hints.hasJoin) {
-            rules.push(RuleConstants.CHOOSE_DEPENDENT);
-        }
-        if(hints.hasAggregates) {
-            rules.push(RuleConstants.PUSH_AGGREGATES);
-        }
-        if(hints.hasJoin) {
-            rules.push(RuleConstants.CHOOSE_JOIN_STRATEGY);
-            rules.push(RuleConstants.RAISE_ACCESS);
-            //after planning the joins, let the criteria be pushed back into place
-            rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
-            rules.push(RuleConstants.PLAN_JOINS);
-        }
-        rules.push(RuleConstants.RAISE_ACCESS);
-        if (hints.hasSetQuery) {
-            rules.push(RuleConstants.PLAN_UNIONS);
-        } 
-        if(hints.hasCriteria || hints.hasJoin) {
-            //after copy criteria, it is no longer necessary to have phantom criteria nodes, so do some cleaning
-            rules.push(RuleConstants.CLEAN_CRITERIA);
-        }
-        if(hints.hasJoin) {
-            rules.push(RuleConstants.COPY_CRITERIA);
-            rules.push(RuleConstants.PUSH_NON_JOIN_CRITERIA);
-        }
-        if(hints.hasVirtualGroups) {
-            rules.push(RuleConstants.MERGE_VIRTUAL);
-        }
-        if(hints.hasCriteria) {
-            rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
-        }
-        if (hints.hasJoin && hints.hasSetQuery) {
-            rules.push(RuleConstants.DECOMPOSE_JOIN);
-            rules.push(RuleConstants.MERGE_VIRTUAL);
-        }
-        if (hints.hasJoin && hints.hasOptionalJoin) {
-            rules.push(RuleConstants.REMOVE_OPTIONAL_JOINS);
-        }
-        rules.push(RuleConstants.PLACE_ACCESS);
-        return rules;
-    }
-
-    private PlanNode executeRules(RuleStack rules, PlanNode plan)
-        throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
-        boolean debug = analysisRecord.recordDebug();
-        while(! rules.isEmpty()) {
-            if(debug) {
-                analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
-            }
-
-            OptimizerRule rule = rules.pop();
-            if(debug) {
-                analysisRecord.println("EXECUTING " + rule); //$NON-NLS-1$
-            }
-
-            plan = rule.execute(plan, metadata, capFinder, rules, analysisRecord, context);
-            if(debug) {
-                analysisRecord.println("\nAFTER: \n" + plan); //$NON-NLS-1$
-            }
-        }
-        return plan;
-    }
-	
-	public PlanNode generatePlan(Command cmd) throws TeiidComponentException, TeiidProcessingException {
-		//cascade the option clause nocache
-		Option savedOption = option;
-		option = cmd.getOption();
-        if (option == null) {
-        	if (savedOption != null) {
-        		option = savedOption;
-        	} 
-        } else if (savedOption != null && savedOption.isNoCache()) { //merge no cache settings
-    		if (savedOption.getNoCacheGroups() == null || savedOption.getNoCacheGroups().isEmpty()) {
-    			if (option.getNoCacheGroups() != null) {
-    				option.getNoCacheGroups().clear(); // full no cache
-    			}
-    		} else if (option.getNoCacheGroups() != null && !option.getNoCacheGroups().isEmpty()) {
-    			for (String noCache : savedOption.getNoCacheGroups()) {
-					option.addNoCacheGroup(noCache); // only groups
-				}
-    		}
-    		option.setNoCache(true);
-        }
-		
-		PlanNode result = null;
-		switch (cmd.getType()) {
-		case Command.TYPE_QUERY:
-			result = createQueryPlan((QueryCommand)cmd);
-			break;
-		case Command.TYPE_INSERT:
-		case Command.TYPE_UPDATE:
-		case Command.TYPE_DELETE:
-		case Command.TYPE_CREATE:
-		case Command.TYPE_DROP:
-			result = createUpdatePlan(cmd);
-			break;
-		case Command.TYPE_STORED_PROCEDURE:
-			result = createStoredProcedurePlan((StoredProcedure)cmd);
-			break;
-		default:
-			throw new AssertionError("Invalid command type"); //$NON-NLS-1$
-		}
-        // Distribute make dependent hints as necessary
-        if (cmd.getOption() != null) {
-	        if(cmd.getOption().getDependentGroups() != null) {
-	            distributeDependentHints(cmd.getOption().getDependentGroups(), result, NodeConstants.Info.MAKE_DEP);
-	        }
-	        if (cmd.getOption().getNotDependentGroups() != null) {
-	            distributeDependentHints(cmd.getOption().getNotDependentGroups(), result, NodeConstants.Info.MAKE_NOT_DEP);
-	        }
-        }
-        this.option = savedOption;
-        return result;
-	}
-
-	PlanNode createUpdatePlan(Command command) throws TeiidComponentException, TeiidProcessingException {
-        // Create top project node - define output columns for stored query / procedure
-        PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
-
-        Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(command, false);
-        projectNode.addGroups(groups);
-
-        // Set output columns
-        List<SingleElementSymbol> cols = command.getProjectedSymbols();
-        projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, cols);
-
-        // Define source of data for stored query / procedure
-        PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
-        sourceNode.setProperty(NodeConstants.Info.ATOMIC_REQUEST, command);
-        sourceNode.setProperty(NodeConstants.Info.VIRTUAL_COMMAND, command);
-        boolean usingTriggerAction = false;
-        if (command instanceof ProcedureContainer) {
-        	ProcedureContainer container = (ProcedureContainer)command;
-        	usingTriggerAction = addNestedProcedure(sourceNode, container);
-        }
-        sourceNode.addGroups(groups);
-
-        attachLast(projectNode, sourceNode);
-
-        //for INTO query, attach source and project nodes
-        if(!usingTriggerAction && command instanceof Insert){
-        	Insert insert = (Insert)command;
-        	if (insert.getQueryExpression() != null) {
-	            PlanNode plan = generatePlan(insert.getQueryExpression());
-	            attachLast(sourceNode, plan);
-	            mergeTempMetadata(insert.getQueryExpression(), insert);
-	            projectNode.setProperty(NodeConstants.Info.INTO_GROUP, insert.getGroup());
-        	}
-        }
-        
-        return projectNode;
-	}
-
-	private boolean addNestedProcedure(PlanNode sourceNode,
-			ProcedureContainer container) throws TeiidComponentException,
-			QueryMetadataException, TeiidProcessingException {
-		String cacheString = "transformation/" + container.getClass().getSimpleName(); //$NON-NLS-1$
-		Command c = (Command)metadata.getFromMetadataCache(container.getGroup().getMetadataID(), cacheString);
-		if (c == null) {
-			c = QueryResolver.expandCommand(container, metadata, analysisRecord);
-			if (c != null) {
-		        Request.validateWithVisitor(new ValidationVisitor(), metadata, c);
-		        metadata.addToMetadataCache(container.getGroup().getMetadataID(), cacheString, c.clone());
-			}
-		} else {
-			c = (Command)c.clone();
-			if (c instanceof CreateUpdateProcedureCommand) {
-				((CreateUpdateProcedureCommand)c).setUserCommand(container);
-			}
-		}
-		if (c != null) {
-			if (c instanceof TriggerAction) {
-				TriggerAction ta = (TriggerAction)c;
-				ProcessorPlan plan = new TriggerActionPlanner().optimize(container, ta, idGenerator, metadata, capFinder, analysisRecord, context);
-			    sourceNode.setProperty(NodeConstants.Info.PROCESSOR_PLAN, plan);
-			    return true;
-			}
-			if (c.getCacheHint() != null) {
-				if (container instanceof StoredProcedure) {
-					boolean noCache = isNoCacheGroup(metadata, ((StoredProcedure) container).getProcedureID(), option);
-					if (!noCache) {
-						if (container.areResultsCachable() && Query.areResultsCachable(container.getProcedureParameters().keySet()) && context.isResultSetCacheEnabled()) {
-							container.getGroup().setGlobalTable(true);
-							container.setCacheHint(c.getCacheHint());
-							recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.LOW, "SimpleQueryResolver.procedure_cache_used", container.getGroup()); //$NON-NLS-1$
-							return false;
-						}
-						recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.MEDIUM, "SimpleQueryResolver.procedure_cache_not_usable", container.getGroup()); //$NON-NLS-1$
-					} else {
-						recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.LOW, "SimpleQueryResolver.procedure_cache_not_used", container.getGroup()); //$NON-NLS-1$
-					}
-				}
-			}
-			//skip the rewrite here, we'll do that in the optimizer
-			//so that we know what the determinism level is.
-			addNestedCommand(sourceNode, container.getGroup(), container, c, false);
-		} else if (container instanceof TranslatableProcedureContainer && !container.getGroup().isTempGroupSymbol() && 
-				!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(container, metadata.getModelID(container.getGroup().getMetadataID()), metadata, capFinder, analysisRecord)) {
-			if (metadata.getUniqueKeysInGroup(container.getGroup().getMetadataID()).isEmpty() 
-					|| !CapabilitiesUtil.supports(Capability.CRITERIA_COMPARE_EQ, metadata.getModelID(container.getGroup().getMetadataID()), metadata, capFinder)) {
-				throw new QueryPlannerException(QueryPlugin.Util.getString("RelationalPlanner.nonpushdown_command", container)); //$NON-NLS-1$
-			}
-			
-			//treat this as an update procedure
-			if (container instanceof Update) {
-				c = QueryRewriter.createUpdateProcedure((Update)container, metadata, context);
-			} else {
-				c = QueryRewriter.createDeleteProcedure((Delete)container, metadata, context);
-			}
-			addNestedCommand(sourceNode, container.getGroup(), container, c, false);
-			return false;
-		}
-		
-		//plan any subqueries in criteria/parameters/values
-		for (SubqueryContainer subqueryContainer : ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(container)) {
-    		ProcessorPlan plan = QueryOptimizer.optimizePlan(subqueryContainer.getCommand(), metadata, null, capFinder, analysisRecord, context);
-    		subqueryContainer.getCommand().setProcessorPlan(plan);
-    		
-    		if (c == null) {
-				RuleCollapseSource.replaceCorrelatedReferences(subqueryContainer);
-			}
-		}
-		return false;
-	}
-
-    PlanNode createStoredProcedurePlan(StoredProcedure storedProc) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-        // Create top project node - define output columns for stored query / procedure
-        PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
-
-        // Set output columns
-        List cols = storedProc.getProjectedSymbols();
-        projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, cols);
-
-        // Define source of data for stored query / procedure
-        PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
-        sourceNode.setProperty(NodeConstants.Info.VIRTUAL_COMMAND, storedProc);
-    	addNestedProcedure(sourceNode, storedProc);
-        
-        hints.hasRelationalProc |= storedProc.isProcedureRelational();
-
-        // Set group on source node
-        sourceNode.addGroup(storedProc.getGroup());
-
-        attachLast(projectNode, sourceNode);
-
-        return projectNode;
-    }
-
-	PlanNode createQueryPlan(QueryCommand command)
-		throws TeiidComponentException, TeiidProcessingException {
-        // Build canonical plan
-    	PlanNode node = null;
-        if(command instanceof Query) {
-            node = createQueryPlan((Query) command);
-        } else {
-            hints.hasSetQuery = true;
-            SetQuery query = (SetQuery)command;
-            PlanNode leftPlan = createQueryPlan( query.getLeftQuery());
-            PlanNode rightPlan = createQueryPlan( query.getRightQuery());
-
-            node = NodeFactory.getNewNode(NodeConstants.Types.SET_OP);
-            node.setProperty(NodeConstants.Info.SET_OPERATION, query.getOperation());
-            node.setProperty(NodeConstants.Info.USE_ALL, query.isAll());
-            
-            attachLast(node, leftPlan);
-            attachLast(node, rightPlan);
-        }
-        
-		if(command.getOrderBy() != null) {
-			node = attachSorting(node, command.getOrderBy());
-		}
-
-        if (command.getLimit() != null) {
-            node = attachTupleLimit(node, command.getLimit(), hints);
-        }
-        
-        return node;
-    }
-
-    private PlanNode createQueryPlan(Query query)
-		throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-
-        PlanNode plan = null;
-
-        if(query.getFrom() != null){
-            FromClause fromClause = mergeClauseTrees(query.getFrom());
-            
-            PlanNode dummyRoot = new PlanNode();
-            
-    		buildTree(fromClause, dummyRoot);
-            
-            plan = dummyRoot.getFirstChild();
-            
-            hints.hasJoin |= plan.getType() == NodeConstants.Types.JOIN;
-
-    		// Attach criteria on top
-    		if(query.getCriteria() != null) {
-    			plan = attachCriteria(plan, query.getCriteria(), false);
-                hints.hasCriteria = true;
-    		}
-
-    		// Attach grouping node on top
-    		if(query.hasAggregates()) {
-    			plan = attachGrouping(plan, query, hints);
-    		}
-
-    		// Attach having criteria node on top
-    		if(query.getHaving() != null) {
-    			plan = attachCriteria(plan, query.getHaving(), true);
-                hints.hasCriteria = true;
-    		}
-            
-        }
-
-		// Attach project on top
-		plan = attachProject(plan, query.getSelect());
-
-		// Attach dup removal on top
-		if(query.getSelect().isDistinct()) {
-			plan = attachDupRemoval(plan);
-		}
-
-		return plan;
-	}
-
-    /**
-     * Merges the from clause into a single join predicate if there are more than 1 from clauses
-     */
-    private static FromClause mergeClauseTrees(From from) {
-        List clauses = from.getClauses();
-        
-        while (clauses.size() > 1) {
-            FromClause first = (FromClause)from.getClauses().remove(0);
-            FromClause second = (FromClause)from.getClauses().remove(0);
-            JoinPredicate jp = new JoinPredicate(first, second, JoinType.JOIN_CROSS);
-            clauses.add(0, jp);
-        }
-        
-        return (FromClause)clauses.get(0);
-    }
-    
-    /**
-     * Build a join plan based on the structure in a clause.  These structures should be
-     * essentially the same tree, but with different objects and details.
-     * @param clause Clause to build tree from
-     * @param parent Parent node to attach join node structure to
-     * @param sourceMap Map of group to source node, used for connecting children to join plan
-     * @param markJoinsInternal Flag saying whether joins built in this method should be marked
-     * as internal
-     * @throws TeiidComponentException 
-     * @throws QueryMetadataException 
-     * @throws TeiidProcessingException 
-     */
-    void buildTree(FromClause clause, PlanNode parent)
-        throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-        
-        PlanNode node = null;
-        
-        if(clause instanceof UnaryFromClause) {
-            // No join required
-            UnaryFromClause ufc = (UnaryFromClause)clause;
-            GroupSymbol group = ufc.getGroup();
-            if (metadata.isVirtualGroup(group.getMetadataID())) {
-            	hints.hasVirtualGroups = true;
-            }
-            Command nestedCommand = ufc.getExpandedCommand();
-            if (nestedCommand == null && !group.isTempGroupSymbol() && !group.isProcedure() 
-            		&& (!(group.getMetadataID() instanceof TempMetadataID) || metadata.getVirtualPlan(group.getMetadataID()) != null)
-        	        && (metadata.isVirtualGroup(group.getMetadataID()))) { 
-            	//must be a view layer
-            	nestedCommand = resolveVirtualGroup(group);
-            }
-            node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
-            if (group.getModelMetadataId() != null) {
-            	node.setProperty(Info.MODEL_ID, group.getModelMetadataId());
-            }
-            node.addGroup(group);
-            if (nestedCommand != null) {
-            	UpdateInfo info = ProcedureContainerResolver.getUpdateInfo(group, metadata);
-            	if (info != null && info.getPartitionInfo() != null && !info.getPartitionInfo().isEmpty()) {
-            		node.setProperty(NodeConstants.Info.PARTITION_INFO, info.getPartitionInfo());
-            	}
-            	addNestedCommand(node, group, nestedCommand, nestedCommand, true);
-            }
-            parent.addLastChild(node);
-        } else if(clause instanceof JoinPredicate) {
-            JoinPredicate jp = (JoinPredicate) clause;
-
-            // Set up new join node corresponding to this join predicate
-            node = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
-            node.setProperty(NodeConstants.Info.JOIN_TYPE, jp.getJoinType());
-            node.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_LOOP);
-            node.setProperty(NodeConstants.Info.JOIN_CRITERIA, jp.getJoinCriteria());
-            
-            if (jp.getJoinType() == JoinType.JOIN_LEFT_OUTER) {
-            	hints.hasOptionalJoin = true;
-            }
-         
-            // Attach join node to parent
-            parent.addLastChild(node);
-
-            // Handle each child
-            FromClause[] clauses = new FromClause[] {jp.getLeftClause(), jp.getRightClause()};
-            for(int i=0; i<2; i++) {
-                buildTree(clauses[i], node);
-
-                // Add groups to joinNode
-                for (PlanNode child : node.getChildren()) {
-                    node.addGroups(child.getGroups());
-                }
-            }
-        } else if (clause instanceof SubqueryFromClause) {
-            SubqueryFromClause sfc = (SubqueryFromClause)clause;
-            GroupSymbol group = sfc.getGroupSymbol();
-            Command nestedCommand = sfc.getCommand();
-            node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
-            if (sfc.isTable()) {
-    		    sfc.getCommand().setCorrelatedReferences(getCorrelatedReferences(parent, node, sfc));
-            }
-            node.addGroup(group);
-            addNestedCommand(node, group, nestedCommand, nestedCommand, true);
-			if (nestedCommand instanceof SetQuery) {
-				Map<ElementSymbol, List<Set<Constant>>> partitionInfo = PartitionAnalyzer.extractPartionInfo((SetQuery)nestedCommand, ResolverUtil.resolveElementsInGroup(group, metadata));
-				if (!partitionInfo.isEmpty()) {
-					node.setProperty(NodeConstants.Info.PARTITION_INFO, partitionInfo);
-				}
-			}
-            hints.hasVirtualGroups = true;
-            parent.addLastChild(node);
-        } else if (clause instanceof TableFunctionReference) {
-        	TableFunctionReference tt = (TableFunctionReference)clause;
-            GroupSymbol group = tt.getGroupSymbol();
-            node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
-            node.setProperty(NodeConstants.Info.TABLE_FUNCTION, tt);
-            tt.setCorrelatedReferences(getCorrelatedReferences(parent, node, tt));
-            node.addGroup(group);
-            parent.addLastChild(node);
-        }
-        
-        if (clause.isOptional()) {
-            node.setProperty(NodeConstants.Info.IS_OPTIONAL, Boolean.TRUE);
-            hints.hasOptionalJoin = true;
-        }
-        
-        if (clause.isMakeDep()) {
-            node.setProperty(NodeConstants.Info.MAKE_DEP, Boolean.TRUE);
-        } else if (clause.isMakeNotDep()) {
-            node.setProperty(NodeConstants.Info.MAKE_NOT_DEP, Boolean.TRUE);
-        }
-    }
-
-	private SymbolMap getCorrelatedReferences(PlanNode parent, PlanNode node,
-			LanguageObject lo) {
-		PlanNode rootJoin = parent;
-		while (rootJoin.getParent() != null && rootJoin.getParent().getType() == NodeConstants.Types.JOIN && !rootJoin.getParent().getGroups().isEmpty()) {
-			rootJoin = rootJoin.getParent();
-		}
-		List<Reference> correlatedReferences = new ArrayList<Reference>();
-		CorrelatedReferenceCollectorVisitor.collectReferences(lo, rootJoin.getGroups(), correlatedReferences);
-		
-		if (correlatedReferences.isEmpty()) {
-			return null;
-		}
-	    SymbolMap map = new SymbolMap();
-	    for (Reference reference : correlatedReferences) {
-			map.addMapping(reference.getExpression(), reference.getExpression());
-		}
-	    node.setProperty(NodeConstants.Info.CORRELATED_REFERENCES, map);
-	    return map;
-	}
-
-	private void addNestedCommand(PlanNode node,
-			GroupSymbol group, Command nestedCommand, Command toPlan, boolean merge) throws TeiidComponentException, QueryMetadataException, TeiidProcessingException {
-		if (nestedCommand instanceof QueryCommand) {
-			//remove unnecessary order by
-        	QueryCommand queryCommand = (QueryCommand)nestedCommand;
-        	if (queryCommand.getLimit() == null) {
-        		queryCommand.setOrderBy(null);
-        	}
-        	if (merge && queryCommand.getWith() != null) {
-        		//TODO: should recontext with and merge
-        		merge = false;
-        	}
-        }
-		node.setProperty(NodeConstants.Info.NESTED_COMMAND, nestedCommand);
-
-		if (merge && nestedCommand instanceof Query && QueryResolver.isXMLQuery((Query)nestedCommand, metadata)) {
-			merge = false;
-		}
-
-		if (merge) {
-			mergeTempMetadata(nestedCommand, parentCommand);
-		    PlanNode childRoot = generatePlan(nestedCommand);
-		    node.addFirstChild(childRoot);
-			List<SingleElementSymbol> projectCols = nestedCommand.getProjectedSymbols();
-			SymbolMap map = SymbolMap.createSymbolMap(group, projectCols, metadata);
-			node.setProperty(NodeConstants.Info.SYMBOL_MAP, map);
-		} else {
-			QueryMetadataInterface actualMetadata = metadata;
-			if (actualMetadata instanceof TempMetadataAdapter) {
-				actualMetadata = ((TempMetadataAdapter)metadata).getMetadata();
-			}
-			ProcessorPlan plan = QueryOptimizer.optimizePlan(toPlan, actualMetadata, idGenerator, capFinder, analysisRecord, context);
-		    node.setProperty(NodeConstants.Info.PROCESSOR_PLAN, plan);
-		}
-	}
-
-	/**
-	 * Attach all criteria above the join nodes.  The optimizer will push these
-	 * criteria down to the appropriate source.
-	 * @param plan Existing plan, which joins all source groups
-	 * @param criteria Criteria from query
-	 * @return Updated tree
-	 */
-	private static PlanNode attachCriteria(PlanNode plan, Criteria criteria, boolean isHaving) {
-	    List<Criteria> crits = Criteria.separateCriteriaByAnd(criteria);
-	    
-	    for (Criteria crit : crits) {
-            PlanNode critNode = createSelectNode(crit, isHaving);
-            attachLast(critNode, plan);
-            plan = critNode;
-        } 
-	    
-		return plan;
-	}
-
-    public static PlanNode createSelectNode(final Criteria crit, boolean isHaving) {
-        PlanNode critNode = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
-        critNode.setProperty(NodeConstants.Info.SELECT_CRITERIA, crit);
-        if (isHaving && !AggregateSymbolCollectorVisitor.getAggregates(crit, false).isEmpty()) {
-            critNode.setProperty(NodeConstants.Info.IS_HAVING, Boolean.TRUE);
-        }
-        // Add groups to crit node
-        critNode.addGroups(GroupsUsedByElementsVisitor.getGroups(crit));
-        critNode.addGroups(GroupsUsedByElementsVisitor.getGroups(critNode.getCorrelatedReferenceElements()));
-        return critNode;
-    }
-
-	/**
-	 * Attach a grouping node at top of tree.
-	 * @param plan Existing plan
-	 * @param groupBy Group by clause, which may be null
-	 * @return Updated plan
-	 */
-	private static PlanNode attachGrouping(PlanNode plan, Query query, PlanHints hints) {
-		PlanNode groupNode = NodeFactory.getNewNode(NodeConstants.Types.GROUP);
-
-		GroupBy groupBy = query.getGroupBy();
-		if(groupBy != null) {
-			groupNode.setProperty(NodeConstants.Info.GROUP_COLS, groupBy.getSymbols());
-            groupNode.addGroups(GroupsUsedByElementsVisitor.getGroups(groupBy));
-		}
-
-		attachLast(groupNode, plan);
-        
-        // Mark in hints
-        hints.hasAggregates = true;
-        
-		return groupNode;
-	}
-
-    /**
-	 * Attach SORT node at top of tree.  The SORT may be pushed down to a source (or sources)
-	 * if possible by the optimizer.
-	 * @param plan Existing plan
-	 * @param orderBy Sort description from the query
-	 * @return Updated plan
-	 */
-	private static PlanNode attachSorting(PlanNode plan, OrderBy orderBy) {
-		PlanNode sortNode = NodeFactory.getNewNode(NodeConstants.Types.SORT);
-		
-		sortNode.setProperty(NodeConstants.Info.SORT_ORDER, orderBy);
-		if (orderBy.hasUnrelated()) {
-			sortNode.setProperty(Info.UNRELATED_SORT, true);
-		}
-		sortNode.addGroups(GroupsUsedByElementsVisitor.getGroups(orderBy));
-
-		attachLast(sortNode, plan);
-		return sortNode;
-	}
-    
-    private static PlanNode attachTupleLimit(PlanNode plan, Limit limit, PlanHints hints) {
-        hints.hasLimit = true;
-        PlanNode limitNode = NodeFactory.getNewNode(NodeConstants.Types.TUPLE_LIMIT);
-        
-        boolean attach = false;
-        if (limit.getOffset() != null) {
-            limitNode.setProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT, limit.getOffset());
-            attach = true;
-        }
-        if (limit.getRowLimit() != null) {
-            limitNode.setProperty(NodeConstants.Info.MAX_TUPLE_LIMIT, limit.getRowLimit());
-            attach = true;
-        }
-        if (attach) {
-            attachLast(limitNode, plan);
-            plan = limitNode;
-        }
-        return plan;
-    }
-
-	/**
-	 * Attach DUP_REMOVE node at top of tree.  The DUP_REMOVE may be pushed down
-	 * to a source (or sources) if possible by the optimizer.
-	 * @param plan Existing plan
-	 * @return Updated plan
-	 */
-	private static PlanNode attachDupRemoval(PlanNode plan) {
-		PlanNode dupNode = NodeFactory.getNewNode(NodeConstants.Types.DUP_REMOVE);
-		attachLast(dupNode, plan);
-		return dupNode;
-	}
-
-	private static PlanNode attachProject(PlanNode plan, Select select) {
-		PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
-		projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, select.getProjectedSymbols());
-
-		// Set groups
-		projectNode.addGroups(GroupsUsedByElementsVisitor.getGroups(select));
-
-		attachLast(projectNode, plan);
-		return projectNode;
-	}
-
-	static final void attachLast(PlanNode parent, PlanNode child) {
-		if(child != null) {
-			parent.addLastChild(child);
-		}
-	}
-
-    /**
-     * Adds temp metadata (if any) of child command to temp metadata
-     * (if any) of parent command.
-     * @param childCommand 
-     * @param parentCommand
-     */
-    static void mergeTempMetadata(
-        Command childCommand,
-        Command parentCommand) {
-        Map childTempMetadata = childCommand.getTemporaryMetadata();
-        if (childTempMetadata != null && !childTempMetadata.isEmpty()){
-            // Add to parent temp metadata
-            Map parentTempMetadata = parentCommand.getTemporaryMetadata();
-            if (parentTempMetadata == null){
-                parentCommand.setTemporaryMetadata(new HashMap(childTempMetadata));
-            } else {
-                parentTempMetadata.putAll(childTempMetadata);
-            }
-        }
-    }
-	
-    private Command resolveVirtualGroup(GroupSymbol virtualGroup)
-    throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-    	
-        QueryNode qnode = null;
-        
-        Object metadataID = virtualGroup.getMetadataID();
-        boolean noCache = isNoCacheGroup(metadata, metadataID, option);
-        boolean isMaterializedGroup = metadata.hasMaterialization(metadataID);
-        String cacheString = SQLConstants.Reserved.SELECT; 
-        String groupName = metadata.getFullName(metadataID);
-        
-        if( isMaterializedGroup) {
-        	Object matMetadataId = metadata.getMaterialization(metadataID);
-        	String matTableName = null;
-        	CacheHint hint = null;
-        	boolean isImplicitGlobal = matMetadataId == null;
-            if (isImplicitGlobal) {
-        		matTableName = MAT_PREFIX + groupName;
-        		matMetadataId = getGlobalTempTableMetadataId(virtualGroup, matTableName, context, metadata, analysisRecord);
-        		hint = ((TempMetadataID)matMetadataId).getCacheHint();
-            } else {
-            	matTableName = metadata.getFullName(matMetadataId);
-            }
-
-        	if(noCache){
-        		//not use cache
-        		qnode = metadata.getVirtualPlan(metadataID);
-        		//TODO: update the table for defaultMat
-        		recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.materialized_table_not_used", virtualGroup, matTableName); //$NON-NLS-1$
-        	}else{
-        		qnode = new QueryNode(groupName, null);
-        		Query query = createMatViewQuery(matMetadataId, matTableName, Arrays.asList(new AllSymbol()), isImplicitGlobal);
-        		query.setCacheHint(hint);
-        		qnode.setCommand(query);
-                cacheString = "matview"; //$NON-NLS-1$
-                recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.Query_was_redirected_to_Mat_table", virtualGroup, matTableName); //$NON-NLS-1$
-        	}
-        } else {
-            // Not a materialized view - query the primary transformation
-            qnode = metadata.getVirtualPlan(metadataID);            
-        }
-
-        Command result = getCommand(virtualGroup, qnode, cacheString, metadata, analysisRecord);   
-        return QueryRewriter.rewrite(result, metadata, context);
-    }
-    
-	public static Query createMatViewQuery(Object matMetadataId, String matTableName, List<? extends SelectSymbol> select, boolean isGlobal) {
-		Query query = new Query();
-		query.setSelect(new Select(select));
-		GroupSymbol gs = new GroupSymbol(matTableName);
-		gs.setGlobalTable(isGlobal);
-		gs.setMetadataID(matMetadataId);
-		query.setFrom(new From(Arrays.asList(new UnaryFromClause(gs))));
-		return query;
-	}
-
-	public static Object getGlobalTempTableMetadataId(GroupSymbol table, String matTableName, CommandContext context, QueryMetadataInterface metadata, AnalysisRecord analysisRecord)
-			throws QueryMetadataException, TeiidComponentException, QueryResolverException, QueryValidatorException {
-		TempMetadataStore store = context.getGlobalTableStore().getMetadataStore();
-		TempMetadataID id = store.getTempGroupID(matTableName);
-		//define the table preserving the primary key
-		if (id == null) {
-			synchronized (table.getMetadataID()) {
-				id = store.getTempGroupID(matTableName);
-				if (id == null) {
-					//this is really just temporary and will be replaced by the real table
-					id = store.addTempGroup(matTableName, ResolverUtil.resolveElementsInGroup(table, metadata), false, true);
-					id.setQueryNode(metadata.getVirtualPlan(table.getMetadataID()));
-					id.setCardinality(metadata.getCardinality(table.getMetadataID()));
-					
-					Object pk = metadata.getPrimaryKey(table.getMetadataID());
-					if (pk != null) {
-						ArrayList<TempMetadataID> primaryKey = resolveIndex(metadata, id, pk);
-						id.setPrimaryKey(primaryKey);
-					}
-					Collection keys = metadata.getUniqueKeysInGroup(table.getMetadataID());
-					for (Object key : keys) {
-						id.addUniqueKey(resolveIndex(metadata, id, key));
-					}
-					Collection indexes = metadata.getIndexesInGroup(table.getMetadataID());
-					for (Object index : indexes) {
-						id.addIndex(resolveIndex(metadata, id, index));
-					}
-					Command c = getCommand(table, metadata.getVirtualPlan(table.getMetadataID()), SQLConstants.Reserved.SELECT, metadata, analysisRecord);
-					CacheHint hint = c.getCacheHint();
-					if (hint != null) {
-						recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.cache_hint_used", table, matTableName, id.getCacheHint()); //$NON-NLS-1$
-					}
-					id.setCacheHint(hint);
-				}
-			}
-		} else if (id.getCacheHint() != null) {
-			recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.cache_hint_used", table, matTableName, id.getCacheHint()); //$NON-NLS-1$
-		}
-		return id;
-	}
-
-	private static ArrayList<TempMetadataID> resolveIndex(
-			QueryMetadataInterface metadata, TempMetadataID id, Object pk)
-			throws TeiidComponentException, QueryMetadataException {
-		List cols = metadata.getElementIDsInKey(pk);
-		ArrayList<TempMetadataID> primaryKey = new ArrayList<TempMetadataID>(cols.size());
-		for (Object coldId : cols) {
-			int pos = metadata.getPosition(coldId) - 1;
-			primaryKey.add(id.getElements().get(pos));
-		}
-		return primaryKey;
-	}
-
-	private static Command getCommand(GroupSymbol virtualGroup, QueryNode qnode,
-			String cacheString, QueryMetadataInterface qmi, AnalysisRecord analysisRecord) throws TeiidComponentException,
-			QueryMetadataException, QueryResolverException,
-			QueryValidatorException {
-		Command result = (Command)qmi.getFromMetadataCache(virtualGroup.getMetadataID(), "transformation/" + cacheString); //$NON-NLS-1$
-        if (result != null) {
-        	result = (Command)result.clone();
-        } else {
-        	result = qnode.getCommand();
-            
-            if (result == null) {
-                try {
-                	result = QueryParser.getQueryParser().parseCommand(qnode.getQuery());
-                } catch(QueryParserException e) {
-                    throw new QueryResolverException(e, "ERR.015.008.0011", QueryPlugin.Util.getString("ERR.015.008.0011", qnode.getGroupName())); //$NON-NLS-1$ //$NON-NLS-2$
-                }
-                
-                //Handle bindings and references
-                List bindings = qnode.getBindings();
-                if (bindings != null){
-                    BindVariableVisitor.bindReferences(result, bindings, qmi);
-                }
-            }
-	        QueryResolver.resolveCommand(result, Collections.EMPTY_MAP, qmi, analysisRecord);
-	        Request.validateWithVisitor(new ValidationVisitor(), qmi, result);
-	        qmi.addToMetadataCache(virtualGroup.getMetadataID(), "transformation/" + cacheString, result.clone()); //$NON-NLS-1$
-        }
-		return result;
-	}
-
-    public static boolean isNoCacheGroup(QueryMetadataInterface metadata,
-                                          Object metadataID,
-                                          Option option) throws QueryMetadataException,
-                                                        TeiidComponentException {
-        if(option == null || !option.isNoCache()){
-            return false;
-        }
-    	if(option.getNoCacheGroups() == null || option.getNoCacheGroups().isEmpty()){
-    		//only OPTION NOCACHE, no group specified
-    		return true;
-    	}       
-    	String fullName = metadata.getFullName(metadataID);
-    	for (String groupName : option.getNoCacheGroups()) {
-            if(groupName.equalsIgnoreCase(fullName)){
-                return true;
-            }
-        }
-        return false;
-    }
-    
-    private static void recordAnnotation(AnalysisRecord analysis, String type, Priority priority, String msgKey, Object... parts) {
-    	if (analysis.recordAnnotations()) {
-    		Annotation annotation = new Annotation(type, 
-                    QueryPlugin.Util.getString(msgKey, parts), 
-                    null, 
-                    priority);
-    		analysis.addAnnotation(annotation);
-    	}
-    }
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java (from rev 2803, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,1225 @@
+/*
+ * 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;
+
+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.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryParserException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.client.plan.Annotation;
+import org.teiid.client.plan.Annotation.Priority;
+import org.teiid.common.buffer.LobManager;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.id.IDGenerator;
+import org.teiid.dqp.internal.process.Request;
+import org.teiid.language.SQLConstants;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.TriggerActionPlanner;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+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.optimizer.relational.plantree.NodeConstants.Info;
+import org.teiid.query.optimizer.relational.rules.CapabilitiesUtil;
+import org.teiid.query.optimizer.relational.rules.CriteriaCapabilityValidatorVisitor;
+import org.teiid.query.optimizer.relational.rules.RuleCollapseSource;
+import org.teiid.query.optimizer.relational.rules.RuleConstants;
+import org.teiid.query.optimizer.relational.rules.RuleMergeCriteria;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
+import org.teiid.query.resolver.ProcedureContainerResolver;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.util.BindVariableVisitor;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.LanguageObject.Util;
+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.lang.Delete;
+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.JoinPredicate;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.Limit;
+import org.teiid.query.sql.lang.Option;
+import org.teiid.query.sql.lang.OrderBy;
+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.Select;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.TableFunctionReference;
+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.navigator.PreOrPostOrderNavigator;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+import org.teiid.query.sql.proc.TriggerAction;
+import org.teiid.query.sql.symbol.AllSymbol;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.SelectSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
+import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.validator.ValidationVisitor;
+import org.teiid.query.validator.UpdateValidator.UpdateInfo;
+
+
+/**
+ * This class generates a relational plan for query execution.  The output of
+ * this class is a {@link org.teiid.query.optimizer.relational.plantree.PlanNode PlanNode}
+ * object - this object then becomes the input to
+ * {@link PlanToProcessConverter PlanToProcessConverter}
+ * to  produce a
+ * {@link org.teiid.query.processor.relational.RelationalPlan RelationalPlan}.
+ */
+public class RelationalPlanner {
+	
+	public static final String MAT_PREFIX = "#MAT_"; //$NON-NLS-1$
+	
+	private AnalysisRecord analysisRecord;
+	private Command parentCommand;
+	private IDGenerator idGenerator;
+	private CommandContext context;
+	private CapabilitiesFinder capFinder;
+	private QueryMetadataInterface metadata;
+	private PlanHints hints = new PlanHints();
+	private Option option;
+	
+    public ProcessorPlan optimize(
+        Command command)
+        throws
+            QueryPlannerException,
+            QueryMetadataException,
+            TeiidComponentException {
+
+        boolean debug = analysisRecord.recordDebug();
+		if(debug) {
+            analysisRecord.println("\n----------------------------------------------------------------------------"); //$NON-NLS-1$
+            analysisRecord.println("GENERATE CANONICAL: \n" + command); //$NON-NLS-1$
+		}   
+		
+		PlanToProcessConverter planToProcessConverter = null;
+        if (context != null) {
+        	planToProcessConverter = context.getPlanToProcessConverter();
+        }
+        if (planToProcessConverter == null) {
+        	planToProcessConverter = new PlanToProcessConverter(metadata, idGenerator, analysisRecord, capFinder);
+        }
+		
+		//plan with
+        List<WithQueryCommand> withList = null;
+        Object modelID = null;
+		boolean supportsWithPushdown = true;
+		List<WithQueryCommand> pushDownWith = null;
+		if (command instanceof QueryCommand) {
+			QueryCommand queryCommand = (QueryCommand)command;
+			final HashSet<String> names = new HashSet<String>();
+			if (queryCommand.getWith() != null) {
+	        	withList = queryCommand.getWith();
+	        	for (WithQueryCommand with : queryCommand.getWith()) {
+	        		Command subCommand = with.getCommand();
+	                ProcessorPlan procPlan = QueryOptimizer.optimizePlan(subCommand, metadata, idGenerator, capFinder, analysisRecord, context);
+	                subCommand.setProcessorPlan(procPlan);
+	                QueryCommand withCommand = CriteriaCapabilityValidatorVisitor.getQueryCommand(procPlan);
+	                if (withCommand != null && supportsWithPushdown) {
+	                	modelID = CriteriaCapabilityValidatorVisitor.validateCommandPushdown(modelID, metadata, capFinder, withCommand);
+	            	}
+	                if (modelID == null) {
+	                	supportsWithPushdown = false;
+	                } else {
+	                	if (pushDownWith == null) {
+	                		pushDownWith = new ArrayList<WithQueryCommand>();
+	                	}
+	                	WithQueryCommand wqc = new WithQueryCommand(with.getGroupSymbol(), with.getColumns(), withCommand);
+	                	pushDownWith.add(wqc);
+	                }
+		        	names.add(with.getGroupSymbol().getCanonicalName());
+				}
+	        	if (modelID != null && supportsWithPushdown) {
+	        		supportsWithPushdown = CapabilitiesUtil.supports(Capability.COMMON_TABLE_EXPRESSIONS, modelID, metadata, capFinder);
+	        	}
+				if (supportsWithPushdown) {
+					addModelIds(command, modelID, names);
+				}
+	        }
+		}
+				
+        PlanNode plan;
+		try {
+			plan = generatePlan(command);
+		} catch (TeiidProcessingException e) {
+			throw new QueryPlannerException(e, e.getMessage());
+		}
+
+		if(debug) {
+            analysisRecord.println("\nCANONICAL PLAN: \n" + plan); //$NON-NLS-1$
+		} 
+
+        // Connect ProcessorPlan to SubqueryContainer (if any) of SELECT or PROJECT nodes
+		connectSubqueryContainers(plan); //TODO: merge with node creation
+        
+        // Set top column information on top node
+        List<SingleElementSymbol> topCols = Util.deepClone(command.getProjectedSymbols(), SingleElementSymbol.class);
+
+        // Build rule set based on hints
+        RuleStack rules = buildRules();
+
+        // Run rule-based optimizer
+        plan = executeRules(rules, plan);
+
+        RelationalPlan result = planToProcessConverter.convert(plan);
+        if (withList != null && supportsWithPushdown) {
+        	QueryCommand queryCommand = CriteriaCapabilityValidatorVisitor.getQueryCommand(result);
+        	if (queryCommand != null) { 
+				if (CriteriaCapabilityValidatorVisitor.validateCommandPushdown(modelID, metadata, capFinder, queryCommand) == null) {
+					supportsWithPushdown = false;
+				} else {
+					queryCommand.setWith(pushDownWith);
+				}
+        	} else {
+        		supportsWithPushdown = false;
+        	}
+        }
+        if (!supportsWithPushdown) {
+        	result.setWith(withList);
+        }
+        result.setOutputElements(topCols);
+        
+        return result;
+    }
+
+    /**
+     * mark all relevant group symbols as being from the modelid
+     * @param command
+     * @param modelID
+     * @param names
+     */
+	private void addModelIds(Command command, final Object modelID,
+			final HashSet<String> names) {
+		PreOrPostOrderNavigator.doVisit(command, new LanguageVisitor() {
+			@Override
+			public void visit(UnaryFromClause obj) {
+				GroupSymbol group = obj.getGroup();
+				if (names.contains(group.getNonCorrelationName().toUpperCase())) {
+					group.setModelMetadataId(modelID);
+				}
+			}
+		}, PreOrPostOrderNavigator.POST_ORDER, true);  
+	}
+
+	public void initialize(Command command, IDGenerator idGenerator,
+			QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
+			AnalysisRecord analysisRecord, CommandContext context) {
+		this.parentCommand = command;
+    	this.idGenerator = idGenerator;
+    	this.metadata = metadata;
+    	this.capFinder = capFinder;
+    	this.analysisRecord = analysisRecord;
+    	this.context = context;
+	}
+
+    private void connectSubqueryContainers(PlanNode plan) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+        Set<GroupSymbol> groupSymbols = getGroupSymbols(plan);
+
+        for (PlanNode node : NodeEditor.findAllNodes(plan, NodeConstants.Types.PROJECT | NodeConstants.Types.SELECT | NodeConstants.Types.JOIN)) {
+            List<SubqueryContainer> subqueryContainers = node.getSubqueryContainers();
+            if (subqueryContainers.isEmpty()){
+            	continue;
+            }
+            Set<GroupSymbol> localGroupSymbols = groupSymbols;
+            if (node.getType() == NodeConstants.Types.JOIN) {
+            	localGroupSymbols = getGroupSymbols(node);
+            }
+            for (SubqueryContainer container : subqueryContainers) {
+                //a clone is needed here because the command could get modified during planning
+                Command subCommand = (Command)container.getCommand().clone(); 
+                ArrayList<Reference> correlatedReferences = new ArrayList<Reference>();
+                CorrelatedReferenceCollectorVisitor.collectReferences(subCommand, localGroupSymbols, correlatedReferences);
+                ProcessorPlan procPlan = QueryOptimizer.optimizePlan(subCommand, metadata, idGenerator, capFinder, analysisRecord, context);
+                container.getCommand().setProcessorPlan(procPlan);
+                if (!correlatedReferences.isEmpty()) {
+	                SymbolMap map = new SymbolMap();
+	                for (Reference reference : correlatedReferences) {
+	    				map.addMapping(reference.getExpression(), reference.getExpression());
+	    			}
+	                container.getCommand().setCorrelatedReferences(map);
+                }
+            }
+            node.addGroups(GroupsUsedByElementsVisitor.getGroups(node.getCorrelatedReferenceElements()));
+        }
+    }
+
+	private static Set<GroupSymbol> getGroupSymbols(PlanNode plan) {
+		Set<GroupSymbol> groupSymbols = new HashSet<GroupSymbol>();
+        for (PlanNode source : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE)) {
+            groupSymbols.addAll(source.getGroups());
+        }
+		return groupSymbols;
+	}
+
+    /**
+     * Distribute and "make (not) dependent" hints specified in the query into the
+     * fully resolved query plan.  This is done after virtual group resolution so
+     * that all groups in the plan are known.  The hint is attached to all SOURCE
+     * nodes for each group that should be made dependent/not dependent.
+     * @param groups List of groups (Strings) to be made dependent
+     * @param plan The canonical plan
+     */
+    private void distributeDependentHints(Collection<String> groups, PlanNode plan, NodeConstants.Info hintProperty)
+        throws QueryMetadataException, TeiidComponentException {
+    
+        if(groups == null || groups.isEmpty()) {
+        	return;
+        }
+        // Get all source nodes
+        List<PlanNode> nodes = NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE);
+
+        // Walk through each dependent group hint and
+        // attach to the correct source node
+        for (String groupName : groups) {
+            // Walk through nodes and apply hint to all that match group name
+            boolean appliedHint = applyHint(nodes, groupName, hintProperty);
+
+            if(! appliedHint) {
+                //check if it is partial group name
+                Collection groupNames = metadata.getGroupsForPartialName(groupName);
+                if(groupNames.size() == 1) {
+                    groupName = (String)groupNames.iterator().next();
+                    appliedHint = applyHint(nodes, groupName, hintProperty);
+                }
+                
+                if(! appliedHint) {
+                	String msg = QueryPlugin.Util.getString("ERR.015.004.0010", groupName); //$NON-NLS-1$
+                	if (this.analysisRecord.recordAnnotations()) {
+                		this.analysisRecord.addAnnotation(new Annotation(Annotation.HINTS, msg, "ignoring hint", Priority.MEDIUM)); //$NON-NLS-1$
+                	}
+                }
+            }
+        }
+    }
+    
+    private static boolean applyHint(List<PlanNode> nodes, String groupName, NodeConstants.Info hintProperty) {
+        boolean appliedHint = false;
+        for (PlanNode node : nodes) {
+            GroupSymbol nodeGroup = node.getGroups().iterator().next();
+            
+            String sDefinition = nodeGroup.getDefinition();
+            
+            if (nodeGroup.getName().equalsIgnoreCase(groupName) 
+             || (sDefinition != null && sDefinition.equalsIgnoreCase(groupName)) ) {
+                node.setProperty(hintProperty, Boolean.TRUE);
+                appliedHint = true;
+            }
+        }
+        return appliedHint;
+    }
+
+    public RuleStack buildRules() {
+        RuleStack rules = new RuleStack();
+
+        rules.push(RuleConstants.COLLAPSE_SOURCE);
+        
+        rules.push(RuleConstants.PLAN_SORTS);
+        
+        //TODO: update plan sorts to take advantage or semi-join ordering
+        if (hints.hasJoin || hints.hasCriteria) {
+            rules.push(new RuleMergeCriteria(idGenerator, capFinder, analysisRecord, context, metadata));
+        }
+
+        if(hints.hasJoin) {
+            rules.push(RuleConstants.IMPLEMENT_JOIN_STRATEGY);
+        }
+        
+        rules.push(RuleConstants.ASSIGN_OUTPUT_ELEMENTS);
+        
+        rules.push(RuleConstants.CALCULATE_COST);
+        
+        if (hints.hasLimit) {
+            rules.push(RuleConstants.PUSH_LIMIT);
+        }
+        if (hints.hasRelationalProc) {
+            rules.push(RuleConstants.PLAN_PROCEDURES);
+        }
+        if(hints.hasJoin) {
+            rules.push(RuleConstants.CHOOSE_DEPENDENT);
+        }
+        if(hints.hasAggregates) {
+            rules.push(RuleConstants.PUSH_AGGREGATES);
+        }
+        if(hints.hasJoin) {
+            rules.push(RuleConstants.CHOOSE_JOIN_STRATEGY);
+            rules.push(RuleConstants.RAISE_ACCESS);
+            //after planning the joins, let the criteria be pushed back into place
+            rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
+            rules.push(RuleConstants.PLAN_JOINS);
+        }
+        rules.push(RuleConstants.RAISE_ACCESS);
+        if (hints.hasSetQuery) {
+            rules.push(RuleConstants.PLAN_UNIONS);
+        } 
+        if(hints.hasCriteria || hints.hasJoin) {
+            //after copy criteria, it is no longer necessary to have phantom criteria nodes, so do some cleaning
+            rules.push(RuleConstants.CLEAN_CRITERIA);
+        }
+        if(hints.hasJoin) {
+            rules.push(RuleConstants.COPY_CRITERIA);
+            rules.push(RuleConstants.PUSH_NON_JOIN_CRITERIA);
+        }
+        if(hints.hasVirtualGroups) {
+            rules.push(RuleConstants.MERGE_VIRTUAL);
+        }
+        if(hints.hasCriteria) {
+            rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
+        }
+        if (hints.hasJoin && hints.hasSetQuery) {
+            rules.push(RuleConstants.DECOMPOSE_JOIN);
+            rules.push(RuleConstants.MERGE_VIRTUAL);
+        }
+        if (hints.hasJoin && hints.hasOptionalJoin) {
+            rules.push(RuleConstants.REMOVE_OPTIONAL_JOINS);
+        }
+        rules.push(RuleConstants.PLACE_ACCESS);
+        return rules;
+    }
+
+    private PlanNode executeRules(RuleStack rules, PlanNode plan)
+        throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+        boolean debug = analysisRecord.recordDebug();
+        while(! rules.isEmpty()) {
+            if(debug) {
+                analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
+            }
+
+            OptimizerRule rule = rules.pop();
+            if(debug) {
+                analysisRecord.println("EXECUTING " + rule); //$NON-NLS-1$
+            }
+
+            plan = rule.execute(plan, metadata, capFinder, rules, analysisRecord, context);
+            if(debug) {
+                analysisRecord.println("\nAFTER: \n" + plan); //$NON-NLS-1$
+            }
+        }
+        return plan;
+    }
+	
+	public PlanNode generatePlan(Command cmd) throws TeiidComponentException, TeiidProcessingException {
+		//cascade the option clause nocache
+		Option savedOption = option;
+		option = cmd.getOption();
+        if (option == null) {
+        	if (savedOption != null) {
+        		option = savedOption;
+        	} 
+        } else if (savedOption != null && savedOption.isNoCache()) { //merge no cache settings
+    		if (savedOption.getNoCacheGroups() == null || savedOption.getNoCacheGroups().isEmpty()) {
+    			if (option.getNoCacheGroups() != null) {
+    				option.getNoCacheGroups().clear(); // full no cache
+    			}
+    		} else if (option.getNoCacheGroups() != null && !option.getNoCacheGroups().isEmpty()) {
+    			for (String noCache : savedOption.getNoCacheGroups()) {
+					option.addNoCacheGroup(noCache); // only groups
+				}
+    		}
+    		option.setNoCache(true);
+        }
+		
+		PlanNode result = null;
+		switch (cmd.getType()) {
+		case Command.TYPE_QUERY:
+			result = createQueryPlan((QueryCommand)cmd);
+			break;
+		case Command.TYPE_INSERT:
+		case Command.TYPE_UPDATE:
+		case Command.TYPE_DELETE:
+		case Command.TYPE_CREATE:
+		case Command.TYPE_DROP:
+			result = createUpdatePlan(cmd);
+			break;
+		case Command.TYPE_STORED_PROCEDURE:
+			result = createStoredProcedurePlan((StoredProcedure)cmd);
+			break;
+		default:
+			throw new AssertionError("Invalid command type"); //$NON-NLS-1$
+		}
+        // Distribute make dependent hints as necessary
+        if (cmd.getOption() != null) {
+	        if(cmd.getOption().getDependentGroups() != null) {
+	            distributeDependentHints(cmd.getOption().getDependentGroups(), result, NodeConstants.Info.MAKE_DEP);
+	        }
+	        if (cmd.getOption().getNotDependentGroups() != null) {
+	            distributeDependentHints(cmd.getOption().getNotDependentGroups(), result, NodeConstants.Info.MAKE_NOT_DEP);
+	        }
+        }
+        this.option = savedOption;
+        return result;
+	}
+
+	PlanNode createUpdatePlan(Command command) throws TeiidComponentException, TeiidProcessingException {
+        // Create top project node - define output columns for stored query / procedure
+        PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+
+        Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(command, false);
+        projectNode.addGroups(groups);
+
+        // Set output columns
+        List<SingleElementSymbol> cols = command.getProjectedSymbols();
+        projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, cols);
+
+        // Define source of data for stored query / procedure
+        PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+        sourceNode.setProperty(NodeConstants.Info.ATOMIC_REQUEST, command);
+        sourceNode.setProperty(NodeConstants.Info.VIRTUAL_COMMAND, command);
+        boolean usingTriggerAction = false;
+        if (command instanceof ProcedureContainer) {
+        	ProcedureContainer container = (ProcedureContainer)command;
+        	usingTriggerAction = addNestedProcedure(sourceNode, container);
+        }
+        sourceNode.addGroups(groups);
+
+        attachLast(projectNode, sourceNode);
+
+        //for INTO query, attach source and project nodes
+        if(!usingTriggerAction && command instanceof Insert){
+        	Insert insert = (Insert)command;
+        	if (insert.getQueryExpression() != null) {
+	            PlanNode plan = generatePlan(insert.getQueryExpression());
+	            attachLast(sourceNode, plan);
+	            mergeTempMetadata(insert.getQueryExpression(), insert);
+	            projectNode.setProperty(NodeConstants.Info.INTO_GROUP, insert.getGroup());
+        	}
+        }
+        
+        return projectNode;
+	}
+
+	private boolean addNestedProcedure(PlanNode sourceNode,
+			ProcedureContainer container) throws TeiidComponentException,
+			QueryMetadataException, TeiidProcessingException {
+		String cacheString = "transformation/" + container.getClass().getSimpleName(); //$NON-NLS-1$
+		Command c = (Command)metadata.getFromMetadataCache(container.getGroup().getMetadataID(), cacheString);
+		if (c == null) {
+			c = QueryResolver.expandCommand(container, metadata, analysisRecord);
+			if (c != null) {
+		        Request.validateWithVisitor(new ValidationVisitor(), metadata, c);
+		        metadata.addToMetadataCache(container.getGroup().getMetadataID(), cacheString, c.clone());
+			}
+		} else {
+			c = (Command)c.clone();
+			if (c instanceof CreateUpdateProcedureCommand) {
+				((CreateUpdateProcedureCommand)c).setUserCommand(container);
+			}
+		}
+		if (c != null) {
+			if (c instanceof TriggerAction) {
+				TriggerAction ta = (TriggerAction)c;
+				ProcessorPlan plan = new TriggerActionPlanner().optimize(container, ta, idGenerator, metadata, capFinder, analysisRecord, context);
+			    sourceNode.setProperty(NodeConstants.Info.PROCESSOR_PLAN, plan);
+			    return true;
+			}
+			if (c.getCacheHint() != null) {
+				if (container instanceof StoredProcedure) {
+					boolean noCache = isNoCacheGroup(metadata, ((StoredProcedure) container).getProcedureID(), option);
+					if (!noCache) {
+						if (context.isResultSetCacheEnabled() && container.areResultsCachable() && LobManager.getLobIndexes(new ArrayList<ElementSymbol>(container.getProcedureParameters().keySet())) == null) {
+							container.getGroup().setGlobalTable(true);
+							container.setCacheHint(c.getCacheHint());
+							recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.LOW, "SimpleQueryResolver.procedure_cache_used", container.getGroup()); //$NON-NLS-1$
+							return false;
+						}
+						recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.MEDIUM, "SimpleQueryResolver.procedure_cache_not_usable", container.getGroup()); //$NON-NLS-1$
+					} else {
+						recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.LOW, "SimpleQueryResolver.procedure_cache_not_used", container.getGroup()); //$NON-NLS-1$
+					}
+				}
+			}
+			//skip the rewrite here, we'll do that in the optimizer
+			//so that we know what the determinism level is.
+			addNestedCommand(sourceNode, container.getGroup(), container, c, false);
+		} else if (container instanceof TranslatableProcedureContainer && !container.getGroup().isTempGroupSymbol() && 
+				!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(container, metadata.getModelID(container.getGroup().getMetadataID()), metadata, capFinder, analysisRecord)) {
+			if (metadata.getUniqueKeysInGroup(container.getGroup().getMetadataID()).isEmpty() 
+					|| !CapabilitiesUtil.supports(Capability.CRITERIA_COMPARE_EQ, metadata.getModelID(container.getGroup().getMetadataID()), metadata, capFinder)) {
+				throw new QueryPlannerException(QueryPlugin.Util.getString("RelationalPlanner.nonpushdown_command", container)); //$NON-NLS-1$
+			}
+			
+			//treat this as an update procedure
+			if (container instanceof Update) {
+				c = QueryRewriter.createUpdateProcedure((Update)container, metadata, context);
+			} else {
+				c = QueryRewriter.createDeleteProcedure((Delete)container, metadata, context);
+			}
+			addNestedCommand(sourceNode, container.getGroup(), container, c, false);
+			return false;
+		}
+		
+		//plan any subqueries in criteria/parameters/values
+		for (SubqueryContainer subqueryContainer : ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(container)) {
+    		ProcessorPlan plan = QueryOptimizer.optimizePlan(subqueryContainer.getCommand(), metadata, null, capFinder, analysisRecord, context);
+    		subqueryContainer.getCommand().setProcessorPlan(plan);
+    		
+    		if (c == null) {
+				RuleCollapseSource.replaceCorrelatedReferences(subqueryContainer);
+			}
+		}
+		return false;
+	}
+
+    PlanNode createStoredProcedurePlan(StoredProcedure storedProc) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+        // Create top project node - define output columns for stored query / procedure
+        PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+
+        // Set output columns
+        List cols = storedProc.getProjectedSymbols();
+        projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, cols);
+
+        // Define source of data for stored query / procedure
+        PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+        sourceNode.setProperty(NodeConstants.Info.VIRTUAL_COMMAND, storedProc);
+    	addNestedProcedure(sourceNode, storedProc);
+        
+        hints.hasRelationalProc |= storedProc.isProcedureRelational();
+
+        // Set group on source node
+        sourceNode.addGroup(storedProc.getGroup());
+
+        attachLast(projectNode, sourceNode);
+
+        return projectNode;
+    }
+
+	PlanNode createQueryPlan(QueryCommand command)
+		throws TeiidComponentException, TeiidProcessingException {
+        // Build canonical plan
+    	PlanNode node = null;
+        if(command instanceof Query) {
+            node = createQueryPlan((Query) command);
+        } else {
+            hints.hasSetQuery = true;
+            SetQuery query = (SetQuery)command;
+            PlanNode leftPlan = createQueryPlan( query.getLeftQuery());
+            PlanNode rightPlan = createQueryPlan( query.getRightQuery());
+
+            node = NodeFactory.getNewNode(NodeConstants.Types.SET_OP);
+            node.setProperty(NodeConstants.Info.SET_OPERATION, query.getOperation());
+            node.setProperty(NodeConstants.Info.USE_ALL, query.isAll());
+            
+            attachLast(node, leftPlan);
+            attachLast(node, rightPlan);
+        }
+        
+		if(command.getOrderBy() != null) {
+			node = attachSorting(node, command.getOrderBy());
+		}
+
+        if (command.getLimit() != null) {
+            node = attachTupleLimit(node, command.getLimit(), hints);
+        }
+        
+        return node;
+    }
+
+    private PlanNode createQueryPlan(Query query)
+		throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+
+        PlanNode plan = null;
+
+        if(query.getFrom() != null){
+            FromClause fromClause = mergeClauseTrees(query.getFrom());
+            
+            PlanNode dummyRoot = new PlanNode();
+            
+    		buildTree(fromClause, dummyRoot);
+            
+            plan = dummyRoot.getFirstChild();
+            
+            hints.hasJoin |= plan.getType() == NodeConstants.Types.JOIN;
+
+    		// Attach criteria on top
+    		if(query.getCriteria() != null) {
+    			plan = attachCriteria(plan, query.getCriteria(), false);
+                hints.hasCriteria = true;
+    		}
+
+    		// Attach grouping node on top
+    		if(query.hasAggregates()) {
+    			plan = attachGrouping(plan, query, hints);
+    		}
+
+    		// Attach having criteria node on top
+    		if(query.getHaving() != null) {
+    			plan = attachCriteria(plan, query.getHaving(), true);
+                hints.hasCriteria = true;
+    		}
+            
+        }
+
+		// Attach project on top
+		plan = attachProject(plan, query.getSelect());
+
+		// Attach dup removal on top
+		if(query.getSelect().isDistinct()) {
+			plan = attachDupRemoval(plan);
+		}
+
+		return plan;
+	}
+
+    /**
+     * Merges the from clause into a single join predicate if there are more than 1 from clauses
+     */
+    private static FromClause mergeClauseTrees(From from) {
+        List clauses = from.getClauses();
+        
+        while (clauses.size() > 1) {
+            FromClause first = (FromClause)from.getClauses().remove(0);
+            FromClause second = (FromClause)from.getClauses().remove(0);
+            JoinPredicate jp = new JoinPredicate(first, second, JoinType.JOIN_CROSS);
+            clauses.add(0, jp);
+        }
+        
+        return (FromClause)clauses.get(0);
+    }
+    
+    /**
+     * Build a join plan based on the structure in a clause.  These structures should be
+     * essentially the same tree, but with different objects and details.
+     * @param clause Clause to build tree from
+     * @param parent Parent node to attach join node structure to
+     * @param sourceMap Map of group to source node, used for connecting children to join plan
+     * @param markJoinsInternal Flag saying whether joins built in this method should be marked
+     * as internal
+     * @throws TeiidComponentException 
+     * @throws QueryMetadataException 
+     * @throws TeiidProcessingException 
+     */
+    void buildTree(FromClause clause, PlanNode parent)
+        throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+        
+        PlanNode node = null;
+        
+        if(clause instanceof UnaryFromClause) {
+            // No join required
+            UnaryFromClause ufc = (UnaryFromClause)clause;
+            GroupSymbol group = ufc.getGroup();
+            if (metadata.isVirtualGroup(group.getMetadataID())) {
+            	hints.hasVirtualGroups = true;
+            }
+            Command nestedCommand = ufc.getExpandedCommand();
+            if (nestedCommand == null && !group.isTempGroupSymbol() && !group.isProcedure() 
+            		&& (!(group.getMetadataID() instanceof TempMetadataID) || metadata.getVirtualPlan(group.getMetadataID()) != null)
+        	        && (metadata.isVirtualGroup(group.getMetadataID()))) { 
+            	//must be a view layer
+            	nestedCommand = resolveVirtualGroup(group);
+            }
+            node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+            if (group.getModelMetadataId() != null) {
+            	node.setProperty(Info.MODEL_ID, group.getModelMetadataId());
+            }
+            node.addGroup(group);
+            if (nestedCommand != null) {
+            	UpdateInfo info = ProcedureContainerResolver.getUpdateInfo(group, metadata);
+            	if (info != null && info.getPartitionInfo() != null && !info.getPartitionInfo().isEmpty()) {
+            		node.setProperty(NodeConstants.Info.PARTITION_INFO, info.getPartitionInfo());
+            	}
+            	addNestedCommand(node, group, nestedCommand, nestedCommand, true);
+            }
+            parent.addLastChild(node);
+        } else if(clause instanceof JoinPredicate) {
+            JoinPredicate jp = (JoinPredicate) clause;
+
+            // Set up new join node corresponding to this join predicate
+            node = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+            node.setProperty(NodeConstants.Info.JOIN_TYPE, jp.getJoinType());
+            node.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_LOOP);
+            node.setProperty(NodeConstants.Info.JOIN_CRITERIA, jp.getJoinCriteria());
+            
+            if (jp.getJoinType() == JoinType.JOIN_LEFT_OUTER) {
+            	hints.hasOptionalJoin = true;
+            }
+         
+            // Attach join node to parent
+            parent.addLastChild(node);
+
+            // Handle each child
+            FromClause[] clauses = new FromClause[] {jp.getLeftClause(), jp.getRightClause()};
+            for(int i=0; i<2; i++) {
+                buildTree(clauses[i], node);
+
+                // Add groups to joinNode
+                for (PlanNode child : node.getChildren()) {
+                    node.addGroups(child.getGroups());
+                }
+            }
+        } else if (clause instanceof SubqueryFromClause) {
+            SubqueryFromClause sfc = (SubqueryFromClause)clause;
+            GroupSymbol group = sfc.getGroupSymbol();
+            Command nestedCommand = sfc.getCommand();
+            node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+            if (sfc.isTable()) {
+    		    sfc.getCommand().setCorrelatedReferences(getCorrelatedReferences(parent, node, sfc));
+            }
+            node.addGroup(group);
+            addNestedCommand(node, group, nestedCommand, nestedCommand, true);
+			if (nestedCommand instanceof SetQuery) {
+				Map<ElementSymbol, List<Set<Constant>>> partitionInfo = PartitionAnalyzer.extractPartionInfo((SetQuery)nestedCommand, ResolverUtil.resolveElementsInGroup(group, metadata));
+				if (!partitionInfo.isEmpty()) {
+					node.setProperty(NodeConstants.Info.PARTITION_INFO, partitionInfo);
+				}
+			}
+            hints.hasVirtualGroups = true;
+            parent.addLastChild(node);
+        } else if (clause instanceof TableFunctionReference) {
+        	TableFunctionReference tt = (TableFunctionReference)clause;
+            GroupSymbol group = tt.getGroupSymbol();
+            node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+            node.setProperty(NodeConstants.Info.TABLE_FUNCTION, tt);
+            tt.setCorrelatedReferences(getCorrelatedReferences(parent, node, tt));
+            node.addGroup(group);
+            parent.addLastChild(node);
+        }
+        
+        if (clause.isOptional()) {
+            node.setProperty(NodeConstants.Info.IS_OPTIONAL, Boolean.TRUE);
+            hints.hasOptionalJoin = true;
+        }
+        
+        if (clause.isMakeDep()) {
+            node.setProperty(NodeConstants.Info.MAKE_DEP, Boolean.TRUE);
+        } else if (clause.isMakeNotDep()) {
+            node.setProperty(NodeConstants.Info.MAKE_NOT_DEP, Boolean.TRUE);
+        }
+    }
+
+	private SymbolMap getCorrelatedReferences(PlanNode parent, PlanNode node,
+			LanguageObject lo) {
+		PlanNode rootJoin = parent;
+		while (rootJoin.getParent() != null && rootJoin.getParent().getType() == NodeConstants.Types.JOIN && !rootJoin.getParent().getGroups().isEmpty()) {
+			rootJoin = rootJoin.getParent();
+		}
+		List<Reference> correlatedReferences = new ArrayList<Reference>();
+		CorrelatedReferenceCollectorVisitor.collectReferences(lo, rootJoin.getGroups(), correlatedReferences);
+		
+		if (correlatedReferences.isEmpty()) {
+			return null;
+		}
+	    SymbolMap map = new SymbolMap();
+	    for (Reference reference : correlatedReferences) {
+			map.addMapping(reference.getExpression(), reference.getExpression());
+		}
+	    node.setProperty(NodeConstants.Info.CORRELATED_REFERENCES, map);
+	    return map;
+	}
+
+	private void addNestedCommand(PlanNode node,
+			GroupSymbol group, Command nestedCommand, Command toPlan, boolean merge) throws TeiidComponentException, QueryMetadataException, TeiidProcessingException {
+		if (nestedCommand instanceof QueryCommand) {
+			//remove unnecessary order by
+        	QueryCommand queryCommand = (QueryCommand)nestedCommand;
+        	if (queryCommand.getLimit() == null) {
+        		queryCommand.setOrderBy(null);
+        	}
+        	if (merge && queryCommand.getWith() != null) {
+        		//TODO: should recontext with and merge
+        		merge = false;
+        	}
+        }
+		node.setProperty(NodeConstants.Info.NESTED_COMMAND, nestedCommand);
+
+		if (merge && nestedCommand instanceof Query && QueryResolver.isXMLQuery((Query)nestedCommand, metadata)) {
+			merge = false;
+		}
+
+		if (merge) {
+			mergeTempMetadata(nestedCommand, parentCommand);
+		    PlanNode childRoot = generatePlan(nestedCommand);
+		    node.addFirstChild(childRoot);
+			List<SingleElementSymbol> projectCols = nestedCommand.getProjectedSymbols();
+			SymbolMap map = SymbolMap.createSymbolMap(group, projectCols, metadata);
+			node.setProperty(NodeConstants.Info.SYMBOL_MAP, map);
+		} else {
+			QueryMetadataInterface actualMetadata = metadata;
+			if (actualMetadata instanceof TempMetadataAdapter) {
+				actualMetadata = ((TempMetadataAdapter)metadata).getMetadata();
+			}
+			ProcessorPlan plan = QueryOptimizer.optimizePlan(toPlan, actualMetadata, idGenerator, capFinder, analysisRecord, context);
+		    node.setProperty(NodeConstants.Info.PROCESSOR_PLAN, plan);
+		}
+	}
+
+	/**
+	 * Attach all criteria above the join nodes.  The optimizer will push these
+	 * criteria down to the appropriate source.
+	 * @param plan Existing plan, which joins all source groups
+	 * @param criteria Criteria from query
+	 * @return Updated tree
+	 */
+	private static PlanNode attachCriteria(PlanNode plan, Criteria criteria, boolean isHaving) {
+	    List<Criteria> crits = Criteria.separateCriteriaByAnd(criteria);
+	    
+	    for (Criteria crit : crits) {
+            PlanNode critNode = createSelectNode(crit, isHaving);
+            attachLast(critNode, plan);
+            plan = critNode;
+        } 
+	    
+		return plan;
+	}
+
+    public static PlanNode createSelectNode(final Criteria crit, boolean isHaving) {
+        PlanNode critNode = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
+        critNode.setProperty(NodeConstants.Info.SELECT_CRITERIA, crit);
+        if (isHaving && !AggregateSymbolCollectorVisitor.getAggregates(crit, false).isEmpty()) {
+            critNode.setProperty(NodeConstants.Info.IS_HAVING, Boolean.TRUE);
+        }
+        // Add groups to crit node
+        critNode.addGroups(GroupsUsedByElementsVisitor.getGroups(crit));
+        critNode.addGroups(GroupsUsedByElementsVisitor.getGroups(critNode.getCorrelatedReferenceElements()));
+        return critNode;
+    }
+
+	/**
+	 * Attach a grouping node at top of tree.
+	 * @param plan Existing plan
+	 * @param groupBy Group by clause, which may be null
+	 * @return Updated plan
+	 */
+	private static PlanNode attachGrouping(PlanNode plan, Query query, PlanHints hints) {
+		PlanNode groupNode = NodeFactory.getNewNode(NodeConstants.Types.GROUP);
+
+		GroupBy groupBy = query.getGroupBy();
+		if(groupBy != null) {
+			groupNode.setProperty(NodeConstants.Info.GROUP_COLS, groupBy.getSymbols());
+            groupNode.addGroups(GroupsUsedByElementsVisitor.getGroups(groupBy));
+		}
+
+		attachLast(groupNode, plan);
+        
+        // Mark in hints
+        hints.hasAggregates = true;
+        
+		return groupNode;
+	}
+
+    /**
+	 * Attach SORT node at top of tree.  The SORT may be pushed down to a source (or sources)
+	 * if possible by the optimizer.
+	 * @param plan Existing plan
+	 * @param orderBy Sort description from the query
+	 * @return Updated plan
+	 */
+	private static PlanNode attachSorting(PlanNode plan, OrderBy orderBy) {
+		PlanNode sortNode = NodeFactory.getNewNode(NodeConstants.Types.SORT);
+		
+		sortNode.setProperty(NodeConstants.Info.SORT_ORDER, orderBy);
+		if (orderBy.hasUnrelated()) {
+			sortNode.setProperty(Info.UNRELATED_SORT, true);
+		}
+		sortNode.addGroups(GroupsUsedByElementsVisitor.getGroups(orderBy));
+
+		attachLast(sortNode, plan);
+		return sortNode;
+	}
+    
+    private static PlanNode attachTupleLimit(PlanNode plan, Limit limit, PlanHints hints) {
+        hints.hasLimit = true;
+        PlanNode limitNode = NodeFactory.getNewNode(NodeConstants.Types.TUPLE_LIMIT);
+        
+        boolean attach = false;
+        if (limit.getOffset() != null) {
+            limitNode.setProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT, limit.getOffset());
+            attach = true;
+        }
+        if (limit.getRowLimit() != null) {
+            limitNode.setProperty(NodeConstants.Info.MAX_TUPLE_LIMIT, limit.getRowLimit());
+            attach = true;
+        }
+        if (attach) {
+            attachLast(limitNode, plan);
+            plan = limitNode;
+        }
+        return plan;
+    }
+
+	/**
+	 * Attach DUP_REMOVE node at top of tree.  The DUP_REMOVE may be pushed down
+	 * to a source (or sources) if possible by the optimizer.
+	 * @param plan Existing plan
+	 * @return Updated plan
+	 */
+	private static PlanNode attachDupRemoval(PlanNode plan) {
+		PlanNode dupNode = NodeFactory.getNewNode(NodeConstants.Types.DUP_REMOVE);
+		attachLast(dupNode, plan);
+		return dupNode;
+	}
+
+	private static PlanNode attachProject(PlanNode plan, Select select) {
+		PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+		projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, select.getProjectedSymbols());
+
+		// Set groups
+		projectNode.addGroups(GroupsUsedByElementsVisitor.getGroups(select));
+
+		attachLast(projectNode, plan);
+		return projectNode;
+	}
+
+	static final void attachLast(PlanNode parent, PlanNode child) {
+		if(child != null) {
+			parent.addLastChild(child);
+		}
+	}
+
+    /**
+     * Adds temp metadata (if any) of child command to temp metadata
+     * (if any) of parent command.
+     * @param childCommand 
+     * @param parentCommand
+     */
+    static void mergeTempMetadata(
+        Command childCommand,
+        Command parentCommand) {
+        Map childTempMetadata = childCommand.getTemporaryMetadata();
+        if (childTempMetadata != null && !childTempMetadata.isEmpty()){
+            // Add to parent temp metadata
+            Map parentTempMetadata = parentCommand.getTemporaryMetadata();
+            if (parentTempMetadata == null){
+                parentCommand.setTemporaryMetadata(new HashMap(childTempMetadata));
+            } else {
+                parentTempMetadata.putAll(childTempMetadata);
+            }
+        }
+    }
+	
+    private Command resolveVirtualGroup(GroupSymbol virtualGroup)
+    throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+    	
+        QueryNode qnode = null;
+        
+        Object metadataID = virtualGroup.getMetadataID();
+        boolean noCache = isNoCacheGroup(metadata, metadataID, option);
+        boolean isMaterializedGroup = metadata.hasMaterialization(metadataID);
+        String cacheString = SQLConstants.Reserved.SELECT; 
+        String groupName = metadata.getFullName(metadataID);
+        
+        if( isMaterializedGroup) {
+        	Object matMetadataId = metadata.getMaterialization(metadataID);
+        	String matTableName = null;
+        	CacheHint hint = null;
+        	boolean isImplicitGlobal = matMetadataId == null;
+            if (isImplicitGlobal) {
+        		matTableName = MAT_PREFIX + groupName;
+        		matMetadataId = getGlobalTempTableMetadataId(virtualGroup, matTableName, context, metadata, analysisRecord);
+        		hint = ((TempMetadataID)matMetadataId).getCacheHint();
+            } else {
+            	matTableName = metadata.getFullName(matMetadataId);
+            }
+
+        	if(noCache){
+        		//not use cache
+        		qnode = metadata.getVirtualPlan(metadataID);
+        		//TODO: update the table for defaultMat
+        		recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.materialized_table_not_used", virtualGroup, matTableName); //$NON-NLS-1$
+        	}else{
+        		qnode = new QueryNode(groupName, null);
+        		Query query = createMatViewQuery(matMetadataId, matTableName, Arrays.asList(new AllSymbol()), isImplicitGlobal);
+        		query.setCacheHint(hint);
+        		qnode.setCommand(query);
+                cacheString = "matview"; //$NON-NLS-1$
+                recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.Query_was_redirected_to_Mat_table", virtualGroup, matTableName); //$NON-NLS-1$
+        	}
+        } else {
+            // Not a materialized view - query the primary transformation
+            qnode = metadata.getVirtualPlan(metadataID);            
+        }
+
+        Command result = getCommand(virtualGroup, qnode, cacheString, metadata, analysisRecord);   
+        return QueryRewriter.rewrite(result, metadata, context);
+    }
+    
+	public static Query createMatViewQuery(Object matMetadataId, String matTableName, List<? extends SelectSymbol> select, boolean isGlobal) {
+		Query query = new Query();
+		query.setSelect(new Select(select));
+		GroupSymbol gs = new GroupSymbol(matTableName);
+		gs.setGlobalTable(isGlobal);
+		gs.setMetadataID(matMetadataId);
+		query.setFrom(new From(Arrays.asList(new UnaryFromClause(gs))));
+		return query;
+	}
+
+	public static Object getGlobalTempTableMetadataId(GroupSymbol table, String matTableName, CommandContext context, QueryMetadataInterface metadata, AnalysisRecord analysisRecord)
+			throws QueryMetadataException, TeiidComponentException, QueryResolverException, QueryValidatorException {
+		TempMetadataStore store = context.getGlobalTableStore().getMetadataStore();
+		TempMetadataID id = store.getTempGroupID(matTableName);
+		//define the table preserving the primary key
+		if (id == null) {
+			synchronized (table.getMetadataID()) {
+				id = store.getTempGroupID(matTableName);
+				if (id == null) {
+					//this is really just temporary and will be replaced by the real table
+					id = store.addTempGroup(matTableName, ResolverUtil.resolveElementsInGroup(table, metadata), false, true);
+					id.setQueryNode(metadata.getVirtualPlan(table.getMetadataID()));
+					id.setCardinality(metadata.getCardinality(table.getMetadataID()));
+					
+					Object pk = metadata.getPrimaryKey(table.getMetadataID());
+					if (pk != null) {
+						ArrayList<TempMetadataID> primaryKey = resolveIndex(metadata, id, pk);
+						id.setPrimaryKey(primaryKey);
+					}
+					Collection keys = metadata.getUniqueKeysInGroup(table.getMetadataID());
+					for (Object key : keys) {
+						id.addUniqueKey(resolveIndex(metadata, id, key));
+					}
+					Collection indexes = metadata.getIndexesInGroup(table.getMetadataID());
+					for (Object index : indexes) {
+						id.addIndex(resolveIndex(metadata, id, index));
+					}
+					Command c = getCommand(table, metadata.getVirtualPlan(table.getMetadataID()), SQLConstants.Reserved.SELECT, metadata, analysisRecord);
+					CacheHint hint = c.getCacheHint();
+					if (hint != null) {
+						recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.cache_hint_used", table, matTableName, id.getCacheHint()); //$NON-NLS-1$
+					}
+					id.setCacheHint(hint);
+				}
+			}
+		} else if (id.getCacheHint() != null) {
+			recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.cache_hint_used", table, matTableName, id.getCacheHint()); //$NON-NLS-1$
+		}
+		return id;
+	}
+
+	private static ArrayList<TempMetadataID> resolveIndex(
+			QueryMetadataInterface metadata, TempMetadataID id, Object pk)
+			throws TeiidComponentException, QueryMetadataException {
+		List cols = metadata.getElementIDsInKey(pk);
+		ArrayList<TempMetadataID> primaryKey = new ArrayList<TempMetadataID>(cols.size());
+		for (Object coldId : cols) {
+			int pos = metadata.getPosition(coldId) - 1;
+			primaryKey.add(id.getElements().get(pos));
+		}
+		return primaryKey;
+	}
+
+	private static Command getCommand(GroupSymbol virtualGroup, QueryNode qnode,
+			String cacheString, QueryMetadataInterface qmi, AnalysisRecord analysisRecord) throws TeiidComponentException,
+			QueryMetadataException, QueryResolverException,
+			QueryValidatorException {
+		Command result = (Command)qmi.getFromMetadataCache(virtualGroup.getMetadataID(), "transformation/" + cacheString); //$NON-NLS-1$
+        if (result != null) {
+        	result = (Command)result.clone();
+        } else {
+        	result = qnode.getCommand();
+            
+            if (result == null) {
+                try {
+                	result = QueryParser.getQueryParser().parseCommand(qnode.getQuery());
+                } catch(QueryParserException e) {
+                    throw new QueryResolverException(e, "ERR.015.008.0011", QueryPlugin.Util.getString("ERR.015.008.0011", qnode.getGroupName())); //$NON-NLS-1$ //$NON-NLS-2$
+                }
+                
+                //Handle bindings and references
+                List bindings = qnode.getBindings();
+                if (bindings != null){
+                    BindVariableVisitor.bindReferences(result, bindings, qmi);
+                }
+            }
+	        QueryResolver.resolveCommand(result, Collections.EMPTY_MAP, qmi, analysisRecord);
+	        Request.validateWithVisitor(new ValidationVisitor(), qmi, result);
+	        qmi.addToMetadataCache(virtualGroup.getMetadataID(), "transformation/" + cacheString, result.clone()); //$NON-NLS-1$
+        }
+		return result;
+	}
+
+    public static boolean isNoCacheGroup(QueryMetadataInterface metadata,
+                                          Object metadataID,
+                                          Option option) throws QueryMetadataException,
+                                                        TeiidComponentException {
+        if(option == null || !option.isNoCache()){
+            return false;
+        }
+    	if(option.getNoCacheGroups() == null || option.getNoCacheGroups().isEmpty()){
+    		//only OPTION NOCACHE, no group specified
+    		return true;
+    	}       
+    	String fullName = metadata.getFullName(metadataID);
+    	for (String groupName : option.getNoCacheGroups()) {
+            if(groupName.equalsIgnoreCase(fullName)){
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    private static void recordAnnotation(AnalysisRecord analysis, String type, Priority priority, String msgKey, Object... parts) {
+    	if (analysis.recordAnnotations()) {
+    		Annotation annotation = new Annotation(type, 
+                    QueryPlugin.Util.getString(msgKey, parts), 
+                    null, 
+                    priority);
+    		analysis.addAnnotation(annotation);
+    	}
+    }
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/processor/xml/XMLUtil.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/xml/XMLUtil.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/processor/xml/XMLUtil.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,117 +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.processor.xml;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.nio.charset.Charset;
-
-import javax.xml.transform.TransformerException;
-
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.FileStore;
-import org.teiid.common.buffer.FileStore.FileStoreOutputStream;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.InputStreamFactory;
-import org.teiid.core.types.SQLXMLImpl;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.types.XMLTranslator;
-
-/** 
- * Utility methods to be used with the XML and XQuery processing.
- */
-public class XMLUtil {
-	
-	public static final class FileStoreInputStreamFactory extends InputStreamFactory {
-		private final FileStore lobBuffer;
-		private final FileStoreOutputStream fsos;
-		private String encoding;
-
-		public FileStoreInputStreamFactory(FileStore lobBuffer, String encoding) {
-			this.encoding = encoding;
-			this.lobBuffer = lobBuffer;
-			fsos = lobBuffer.createOutputStream(DataTypeManager.MAX_LOB_MEMORY_BYTES);
-			this.lobBuffer.setCleanupReference(this);
-		}
-
-		@Override
-		public InputStream getInputStream() throws IOException {
-			if (!fsos.bytesWritten()) {
-				return new ByteArrayInputStream(fsos.getBuffer(), 0, fsos.getCount());
-			}
-			//TODO: adjust the buffer size, and/or develop a shared buffer strategy
-			return new BufferedInputStream(lobBuffer.createInputStream(0));
-		}
-
-		@Override
-		public long getLength() {
-			return lobBuffer.getLength();
-		}
-
-		public Writer getWriter() {
-			return new OutputStreamWriter(fsos, Charset.forName(encoding));
-		}
-		
-		public FileStoreOutputStream getOuputStream() {
-			return fsos;
-		}
-
-		@Override
-		public void free() throws IOException {
-			lobBuffer.remove();
-		}
-	}
-
-    /**
-     * This method saves the given XML object to the buffer manager's disk process
-     * Documents less than the maxMemorySize will be held directly in memory
-     */
-    public static SQLXMLImpl saveToBufferManager(BufferManager bufferMgr, XMLTranslator translator) 
-        throws TeiidComponentException, TeiidProcessingException {        
-        boolean success = false;
-        final FileStore lobBuffer = bufferMgr.createFileStore("xml"); //$NON-NLS-1$
-        FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(lobBuffer, Streamable.ENCODING);
-        try{  
-        	Writer writer = fsisf.getWriter();
-            translator.translate(writer);
-            writer.close();
-            success = true;
-            return new SQLXMLImpl(fsisf);
-        } catch(IOException e) {
-            throw new TeiidComponentException(e);
-        } catch(TransformerException e) {
-            throw new TeiidProcessingException(e);
-        } finally {
-        	if (!success && lobBuffer != null) {
-        		lobBuffer.remove();
-        	}
-        }
-    }
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/processor/xml/XMLUtil.java (from rev 2803, trunk/engine/src/main/java/org/teiid/query/processor/xml/XMLUtil.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/processor/xml/XMLUtil.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/processor/xml/XMLUtil.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,122 @@
+/*
+ * 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.processor.xml;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.nio.charset.Charset;
+
+import javax.xml.transform.TransformerException;
+
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.FileStore;
+import org.teiid.common.buffer.FileStore.FileStoreOutputStream;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.SQLXMLImpl;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.types.XMLTranslator;
+
+/** 
+ * Utility methods to be used with the XML and XQuery processing.
+ */
+public class XMLUtil {
+	
+	public static final class FileStoreInputStreamFactory extends InputStreamFactory {
+		private final FileStore lobBuffer;
+		private final FileStoreOutputStream fsos;
+		private String encoding;
+
+		public FileStoreInputStreamFactory(FileStore lobBuffer, String encoding) {
+			this.encoding = encoding;
+			this.lobBuffer = lobBuffer;
+			fsos = lobBuffer.createOutputStream(DataTypeManager.MAX_LOB_MEMORY_BYTES);
+			this.lobBuffer.setCleanupReference(this);
+		}
+
+		@Override
+		public InputStream getInputStream() throws IOException {
+			if (!fsos.bytesWritten()) {
+				return new ByteArrayInputStream(fsos.getBuffer(), 0, fsos.getCount());
+			}
+			//TODO: adjust the buffer size, and/or develop a shared buffer strategy
+			return new BufferedInputStream(lobBuffer.createInputStream(0));
+		}
+
+		@Override
+		public long getLength() {
+			return lobBuffer.getLength();
+		}
+
+		public Writer getWriter() {
+			return new OutputStreamWriter(fsos, Charset.forName(encoding));
+		}
+		
+		public FileStoreOutputStream getOuputStream() {
+			return fsos;
+		}
+
+		@Override
+		public void free() throws IOException {
+			lobBuffer.remove();
+		}
+		
+		@Override
+		public boolean isPersistent() {
+			return true;
+		}
+	}
+
+    /**
+     * This method saves the given XML object to the buffer manager's disk process
+     * Documents less than the maxMemorySize will be held directly in memory
+     */
+    public static SQLXMLImpl saveToBufferManager(BufferManager bufferMgr, XMLTranslator translator) 
+        throws TeiidComponentException, TeiidProcessingException {        
+        boolean success = false;
+        final FileStore lobBuffer = bufferMgr.createFileStore("xml"); //$NON-NLS-1$
+        FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(lobBuffer, Streamable.ENCODING);
+        try{  
+        	Writer writer = fsisf.getWriter();
+            translator.translate(writer);
+            writer.close();
+            success = true;
+            return new SQLXMLImpl(fsisf);
+        } catch(IOException e) {
+            throw new TeiidComponentException(e);
+        } catch(TransformerException e) {
+            throw new TeiidProcessingException(e);
+        } finally {
+        	if (!success && lobBuffer != null) {
+        		lobBuffer.remove();
+        	}
+        }
+    }
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,1097 +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.resolver.util;
-
-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.LinkedHashMap;
-import java.util.LinkedHashSet;
-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.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.UnresolvedSymbolDescription;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.TransformationException;
-import org.teiid.core.types.DataTypeManager.DefaultDataTypes;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.metadata.GroupInfo;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.StoredProcedureInfo;
-import org.teiid.query.metadata.SupportConstants;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.optimizer.relational.rules.RuleChooseJoinStrategy;
-import org.teiid.query.optimizer.relational.rules.RuleRaiseAccess;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.FromClause;
-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.OrderBy;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.symbol.AbstractCaseExpression;
-import org.teiid.query.sql.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.AliasSymbol;
-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.SelectSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-
-
-/**
- * Utilities used during resolution
- */
-public class ResolverUtil {
-
-    public static class ResolvedLookup {
-		private GroupSymbol group;
-		private ElementSymbol keyElement;
-		private ElementSymbol returnElement;
-		
-		void setGroup(GroupSymbol group) {
-			this.group = group;
-		}
-		public GroupSymbol getGroup() {
-			return group;
-		}
-		void setKeyElement(ElementSymbol keyElement) {
-			this.keyElement = keyElement;
-		}
-		public ElementSymbol getKeyElement() {
-			return keyElement;
-		}
-		void setReturnElement(ElementSymbol returnElement) {
-			this.returnElement = returnElement;
-		}
-		public ElementSymbol getReturnElement() {
-			return returnElement;
-		}
-	}
-
-	// Can't construct
-    private ResolverUtil() {}
-
-    /*
-     *                        Type Conversion Utilities
-     */
-
-    /**
-     * Gets the most specific type to which all the given types have an implicit
-     * conversion. The method decides a common type as follows:
-     * <ul>
-     *   <li>If one or more of the given types is a candidate, then this method
-     *       will return the candidate that occurs first in the given array.
-     *       This is why the order of the names in the array is important. </li>
-     *   <li>Otherwise, if none of them is a candidate, this method will attempt
-     *       to find a common type to which all of them can be implicitly
-     *       converted.</li>
-     *   <li>Otherwise this method is unable to find a common type to which all
-     *       the given types can be implicitly converted, and therefore returns
-     *       a null.</li>
-     * </ul>
-     * @param typeNames an ordered array of unique type names.
-     * @return a type name to which all the given types can be converted
-     */
-    public static String getCommonType(String[] typeNames) {
-        if (typeNames == null || typeNames.length == 0) {
-            return null;
-        }
-        // If there is only one type, then simply return it
-        if (typeNames.length == 1) {
-            return typeNames[0];
-        }
-        // A type can be implicitly converted to itself, so we put the implicit
-        // conversions as well as the original type in the working list of
-        // conversions.
-        HashSet<String> commonConversions = new LinkedHashSet<String>();
-        commonConversions.add(typeNames[0]);
-        commonConversions.addAll(DataTypeManager.getImplicitConversions(typeNames[0]));
-        for (int i = 1; i < typeNames.length; i++ ) {
-            HashSet<String> conversions = new LinkedHashSet<String>(DataTypeManager.getImplicitConversions(typeNames[i]));
-            conversions.add(typeNames[i]);
-            // Equivalent to set intersection
-            commonConversions.retainAll(conversions);
-        }
-        if (commonConversions.isEmpty()) {
-            return null;
-        }
-        for (int i = 0; i < typeNames.length; i++) {
-            if (commonConversions.contains(typeNames[i])) {
-                return typeNames[i];
-            }
-        }
-    	commonConversions.remove(DefaultDataTypes.STRING);
-        commonConversions.remove(DefaultDataTypes.OBJECT);
-        if (!commonConversions.isEmpty()) {
-            return commonConversions.iterator().next(); 
-        }
-        return null;
-    }
-
-    /**
-     * Gets whether there exists an implicit conversion from the source type to
-     * the target type
-     * @param fromType
-     * @param toType
-     * @return true if there exists an implicit conversion from the
-     * <code>fromType</code> to the <code>toType</code>.
-     */
-    public static boolean canImplicitlyConvert(String fromType, String toType) {
-        if (fromType.equals(toType)) return true;
-        return DataTypeManager.isImplicitConversion(fromType, toType);
-    }
-
-    /**
-     * Replaces a sourceExpression with a conversion of the source expression
-     * to the target type. If the source type and target type are the same,
-     * this method does nothing.
-     * @param sourceExpression
-     * @param targetTypeName
-     * @return
-     * @throws QueryResolverException 
-     */
-    public static Expression convertExpression(Expression sourceExpression, String targetTypeName, QueryMetadataInterface metadata) throws QueryResolverException {
-        return convertExpression(sourceExpression,
-                                 DataTypeManager.getDataTypeName(sourceExpression.getType()),
-                                 targetTypeName, metadata);
-    }
-
-    /**
-     * Replaces a sourceExpression with a conversion of the source expression
-     * to the target type. If the source type and target type are the same,
-     * this method does nothing.
-     * @param sourceExpression
-     * @param sourceTypeName
-     * @param targetTypeName
-     * @return
-     * @throws QueryResolverException 
-     */
-    public static Expression convertExpression(Expression sourceExpression, String sourceTypeName, String targetTypeName, QueryMetadataInterface metadata) throws QueryResolverException {
-        if (sourceTypeName.equals(targetTypeName)) {
-            return sourceExpression;
-        }
-        
-        if(canImplicitlyConvert(sourceTypeName, targetTypeName) 
-                        || (sourceExpression instanceof Constant && convertConstant(sourceTypeName, targetTypeName, (Constant)sourceExpression) != null)) {
-            return getConversion(sourceExpression, sourceTypeName, targetTypeName, true, metadata.getFunctionLibrary());
-        }
-
-        //Expression is wrong type and can't convert
-        throw new QueryResolverException("ERR.015.008.0041", QueryPlugin.Util.getString("ERR.015.008.0041", new Object[] {targetTypeName, sourceExpression, sourceTypeName})); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    public static Constant convertConstant(String sourceTypeName,
-                                           String targetTypeName,
-                                           Constant constant) {
-        if (!DataTypeManager.isTransformable(sourceTypeName, targetTypeName)) {
-        	return null;
-        }
-
-        try {
-	        //try to get the converted constant, if this fails then it is not in a valid format
-	        Constant result = getProperlyTypedConstant(constant.getValue(), DataTypeManager.getDataTypeClass(targetTypeName));
-	        
-	        if (DataTypeManager.DefaultDataTypes.STRING.equals(sourceTypeName)) {
-	        	if (DataTypeManager.DefaultDataTypes.CHAR.equals(targetTypeName)) {
-	        		String value = (String)constant.getValue();
-	        		if (value != null && value.length() != 1) {
-	        			return null;
-	        		}
-	        	}
-	        	return result;
-	        }
-	        
-	        //for non-strings, ensure that the conversion is consistent
-	        if (!DataTypeManager.isTransformable(targetTypeName, sourceTypeName)) {
-	        	return null;
-	        }
-        
-	        if (!(constant.getValue() instanceof Comparable)) {
-	        	return null; //this is the case for xml constants
-	        }
-	        
-	        Constant reverse = getProperlyTypedConstant(result.getValue(), constant.getType());
-	        
-	        if (((Comparable)constant.getValue()).compareTo(reverse.getValue()) == 0) {
-	            return result;
-	        }
-        } catch (QueryResolverException e) {
-        	
-        }
-            
-        return null;
-    }
-
-    public static Function getConversion(Expression sourceExpression,
-                                            String sourceTypeName,
-                                            String targetTypeName,
-                                            boolean implicit, FunctionLibrary library) {
-        Class<?> srcType = DataTypeManager.getDataTypeClass(sourceTypeName);
-
-        FunctionDescriptor fd = library.findTypedConversionFunction(srcType, DataTypeManager.getDataTypeClass(targetTypeName));
-
-        Function conversion = new Function(fd.getName(), new Expression[] { sourceExpression, new Constant(targetTypeName) });
-        conversion.setType(DataTypeManager.getDataTypeClass(targetTypeName));
-        conversion.setFunctionDescriptor(fd);
-        if (implicit) {
-        	conversion.makeImplicit();
-        }
-
-        return conversion;
-    }
-
-    /**
-     * Utility to set the type of an expression if it is a Reference and has a null type.
-     * @param expression the expression to test
-     * @param targetType the target type, if the expression's type is null.
-     * @throws QueryResolverException if unable to set the reference type to the target type.
-     */
-    public static void setDesiredType(Expression expression, Class<?> targetType, LanguageObject surroundingExpression) throws QueryResolverException {
-        if (expression instanceof Reference) {
-        	Reference ref = (Reference)expression;
-        	if (ref.isPositional() && ref.getType() == null) {
-	        	if (targetType == null) {
-	        		throw new QueryResolverException("ERR.015.008.0026", QueryPlugin.Util.getString("ERR.015.008.0026", surroundingExpression)); //$NON-NLS-1$ //$NON-NLS-2$
-	        	}
-	            ref.setType(targetType);
-        	}
-        } else if (expression instanceof Function) {
-        	Function f = (Function)expression;
-        	if (f.getType() == null) {
-	        	f.setType(targetType);
-        	}
-        }
-    }
-    
-	/**
-	 * Attempt to resolve the order by throws QueryResolverException if the
-	 * symbol is not of SingleElementSymbol type
-	 * 
-	 * @param orderBy
-	 * @param fromClauseGroups
-	 *            groups of the FROM clause of the query (for resolving
-	 *            ambiguous unqualified element names), or empty List if a Set
-	 *            Query Order By is being resolved
-	 * @param knownElements
-	 *            resolved elements from SELECT clause, which are only ones
-	 *            allowed to be in ORDER BY
-	 * @param metadata
-	 *            QueryMetadataInterface
-	 * @param isSimpleQuery
-	 */
-    public static void resolveOrderBy(OrderBy orderBy, QueryCommand command, QueryMetadataInterface metadata)
-        throws QueryResolverException, QueryMetadataException, TeiidComponentException {
-
-    	List<SingleElementSymbol> knownElements = command.getProjectedQuery().getSelect().getProjectedSymbols();
-    	
-    	boolean isSimpleQuery = false;
-    	List fromClauseGroups = Collections.emptyList();
-        
-        if (command instanceof Query) {
-        	Query query = (Query)command;
-        	isSimpleQuery = !query.getSelect().isDistinct() && query.getGroupBy() == null;
-        	if (query.getFrom() != null) {
-        		fromClauseGroups = query.getFrom().getGroups();
-        	}
-        }
-    	
-        // Cached state, if needed
-        String[] knownShortNames = new String[knownElements.size()];
-        List<Expression> expressions = new ArrayList<Expression>(knownElements.size());
-
-        for(int i=0; i<knownElements.size(); i++) {
-            SingleElementSymbol knownSymbol = knownElements.get(i);
-            expressions.add(SymbolMap.getExpression(knownSymbol));
-            if (knownSymbol instanceof ExpressionSymbol) {
-                continue;
-            }
-            
-            String name = knownSymbol.getShortName();
-            
-            knownShortNames[i] = name;
-        }
-
-        for (int i = 0; i < orderBy.getVariableCount(); i++) {
-        	SingleElementSymbol sortKey = orderBy.getVariable(i);
-        	if (sortKey instanceof ElementSymbol) {
-        		ElementSymbol symbol = (ElementSymbol)sortKey;
-        		String groupPart = metadata.getGroupName(symbol.getName());
-        		String symbolName = symbol.getName();
-        		String shortName = symbol.getShortName();
-        		if (groupPart == null) {
-        			int position = -1;
-    				SingleElementSymbol matchedSymbol = null;
-    				// walk the SELECT col short names, looking for a match on the current ORDER BY 'short name'
-    				for(int j=0; j<knownShortNames.length; j++) {
-    					if( !shortName.equalsIgnoreCase( knownShortNames[j] )) {
-    						continue;
-    					}
-    			        // if we already have a matched symbol, matching again here means it is duplicate/ambiguous
-    			        if(matchedSymbol != null) {
-    			        	if (!matchedSymbol.equals(knownElements.get(j))) {
-    			        		throw new QueryResolverException("ERR.015.008.0042", QueryPlugin.Util.getString("ERR.015.008.0042", symbolName)); //$NON-NLS-1$ //$NON-NLS-2$
-    			        	}
-    			        	continue;
-    			        }
-    			        matchedSymbol = knownElements.get(j);
-    			        position = j;
-    				}
-    				if (matchedSymbol != null) {
-    				    TempMetadataID tempMetadataID = new TempMetadataID(symbol.getName(), matchedSymbol.getType());
-    				    symbol.setMetadataID(tempMetadataID);
-    				    symbol.setType(matchedSymbol.getType());
-    				}
-                    if (position != -1) {
-                        orderBy.setExpressionPosition(i, position);
-                        continue;
-                    }
-        		}
-        	} else if (sortKey instanceof ExpressionSymbol) {
-        		// check for legacy positional
-    			ExpressionSymbol es = (ExpressionSymbol)sortKey;
-        		if (es.getExpression() instanceof Constant) {
-            		Constant c = (Constant)es.getExpression();
-        		    int elementOrder = Integer.valueOf(c.getValue().toString()).intValue();
-        		    // adjust for the 1 based index.
-        		    if (elementOrder > knownElements.size() || elementOrder < 1) {
-            		    throw new QueryResolverException(QueryPlugin.Util.getString("SQLParser.non_position_constant", c)); //$NON-NLS-1$
-        		    }
-        		    orderBy.setExpressionPosition(i, elementOrder - 1);
-        		    continue;
-        		}
-        	}
-        	//handle order by expressions        	
-        	if (command instanceof SetQuery) {
-    			throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.setquery_order_expression", sortKey)); //$NON-NLS-1$	 
-    		}
-        	for (ElementSymbol symbol : ElementCollectorVisitor.getElements(sortKey, false)) {
-        		try {
-        	    	ResolverVisitor.resolveLanguageObject(symbol, fromClauseGroups, command.getExternalGroupContexts(), metadata);
-        	    } catch(QueryResolverException e) {
-        	    	throw new QueryResolverException(e, "ERR.015.008.0043", QueryPlugin.Util.getString("ERR.015.008.0043", symbol.getName()) );//$NON-NLS-1$ //$NON-NLS-2$
-        	    } 
-			}
-            ResolverVisitor.resolveLanguageObject(sortKey, metadata);
-            
-            int index = expressions.indexOf(SymbolMap.getExpression(sortKey));
-            if (index == -1 && !isSimpleQuery) {
-    	        throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.invalid_unrelated", sortKey)); //$NON-NLS-1$
-        	}
-        	orderBy.setExpressionPosition(i, index);
-        }
-    }
-    
-    /** 
-     * Get the default value for the parameter, which could be null
-     * if the parameter is set to NULLABLE.  If no default is available,
-     * a QueryResolverException will be thrown.
-     * 
-     * @param symbol ElementSymbol retrieved from metadata, fully-resolved
-     * @param metadata QueryMetadataInterface
-     * @return expr param (if it is non-null) or default value (if there is one)
-     * or null Constant (if parameter is optional and therefore allows this)
-     * @throws QueryResolverException if expr is null, parameter is required and no
-     * default value is defined
-     * @throws QueryMetadataException for error retrieving metadata
-     * @throws TeiidComponentException
-     * @since 4.3
-     */
-	public static Expression getDefault(ElementSymbol symbol, QueryMetadataInterface metadata) throws TeiidComponentException, QueryMetadataException, QueryResolverException {
-        //Check if there is a default value, if so use it
-		Object mid = symbol.getMetadataID();
-    	Class type = symbol.getType();
-    	String name = symbol.getCanonicalName();
-		
-        Object defaultValue = metadata.getDefaultValue(mid);
-        
-        if (defaultValue == null && !metadata.elementSupports(mid, SupportConstants.Element.NULL)) {
-            throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.required_param", name)); //$NON-NLS-1$
-        }
-        
-        return getProperlyTypedConstant(defaultValue, type);
-	}    
-    
-    /** 
-     * Construct a Constant with proper type, given the String default
-     * value for the parameter and the parameter type.  Throw a
-     * QueryResolverException if the String can't be transformed.
-     * @param defaultValue, either null or a String
-     * @param parameterType modeled type of parameter (MetaMatrix runtime type)
-     * @return Constant with proper type and default value Object of proper Class.  Will
-     * be null Constant if defaultValue is null.
-     * @throws QueryResolverException if TransformationException is encountered
-     * @since 4.3
-     */
-    private static Constant getProperlyTypedConstant(Object defaultValue,
-                                                Class parameterType)
-    throws QueryResolverException{
-        try {
-            Object newValue = DataTypeManager.transformValue(defaultValue, parameterType);
-            return new Constant(newValue, parameterType);
-        } catch (TransformationException e) {
-            throw new QueryResolverException(e, QueryPlugin.Util.getString("ResolverUtil.error_converting_value_type", defaultValue, defaultValue.getClass(), parameterType)); //$NON-NLS-1$
-        }
-    }
-
-    /**
-     * Returns the resolved elements in the given group.  This method has the side effect of caching the resolved elements on the group object.
-     * The resolved elements may not contain non-selectable columns depending on the metadata first used for resolving.
-     * 
-     */
-    public static List<ElementSymbol> resolveElementsInGroup(GroupSymbol group, QueryMetadataInterface metadata)
-    throws QueryMetadataException, TeiidComponentException {
-        return new ArrayList<ElementSymbol>(getGroupInfo(group, metadata).getSymbolList());
-    }
-    
-	static GroupInfo getGroupInfo(GroupSymbol group,
-			QueryMetadataInterface metadata)
-			throws TeiidComponentException, QueryMetadataException {
-		String key = GroupInfo.CACHE_PREFIX + group.getCanonicalName();
-		GroupInfo groupInfo = (GroupInfo)metadata.getFromMetadataCache(group.getMetadataID(), key);
-    	
-        if (groupInfo == null) {
-        	group = group.clone();
-            // get all elements from the metadata
-            List elementIDs = metadata.getElementIDsInGroupID(group.getMetadataID());
-
-    		LinkedHashMap<Object, ElementSymbol> symbols = new LinkedHashMap<Object, ElementSymbol>(elementIDs.size());
-                        
-            boolean groupIsAliased = group.getDefinition() != null;
-            
-            for (Object elementID : elementIDs) {
-                String elementName = metadata.getFullName(elementID);
-                String fullName = elementName;
-    			// This is only really needed if the group is an ALIAS.  Doing the check outside the loop
-                // and NOT doing unnecessary work if Aliased group.
-                if(groupIsAliased) {
-                	String shortName = metadata.getShortElementName(elementName);
-                    fullName = metadata.getFullElementName(group.getName(), shortName);
-                }
-
-                // Form an element symbol from the ID
-                ElementSymbol element = new ElementSymbol(fullName);
-                element.setGroupSymbol(group);
-                element.setMetadataID(elementID);
-                element.setType( DataTypeManager.getDataTypeClass(metadata.getElementType(element.getMetadataID())) );
-
-                symbols.put(elementID, element);
-            }
-            groupInfo = new GroupInfo(symbols);
-            metadata.addToMetadataCache(group.getMetadataID(), key, groupInfo);
-        }
-		return groupInfo;
-	}
-    
-    /**
-     * When access patterns are flattened, they are an approximation the user
-     * may need to enter as criteria.
-     *  
-     * @param metadata
-     * @param groups
-     * @param flatten
-     * @return
-     * @throws TeiidComponentException
-     * @throws QueryMetadataException
-     */
-	public static List getAccessPatternElementsInGroups(final QueryMetadataInterface metadata, Collection groups, boolean flatten) throws TeiidComponentException, QueryMetadataException {
-		List accessPatterns = null;
-		Iterator i = groups.iterator();
-		while (i.hasNext()){
-		    
-		    GroupSymbol group = (GroupSymbol)i.next();
-		    
-		    //Check this group for access pattern(s).
-		    Collection accessPatternIDs = metadata.getAccessPatternsInGroup(group.getMetadataID());
-		    if (accessPatternIDs != null && accessPatternIDs.size() > 0){
-		        Iterator j = accessPatternIDs.iterator();
-		        if (accessPatterns == null){
-		            accessPatterns = new ArrayList();
-		        }
-		        while (j.hasNext()) {
-		        	List elements = metadata.getElementIDsInAccessPattern(j.next());
-		        	GroupInfo groupInfo = getGroupInfo(group, metadata);
-		        	List result = new ArrayList(elements.size());
-		        	for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
-		    			Object id = iterator.next();
-		    			ElementSymbol symbol = groupInfo.getSymbol(id);
-		    			assert symbol != null;
-		    			result.add(symbol);
-		    		}
-		        	if (flatten) {
-		        		accessPatterns.addAll(result);
-		        	} else {
-		        		accessPatterns.add(new AccessPattern(result));
-		        	}
-		        }
-		    }
-		}
-                
-		return accessPatterns;
-	}
-
-    public static void resolveLimit(Limit limit) throws QueryResolverException {
-        if (limit.getOffset() != null) {
-            setDesiredType(limit.getOffset(), DataTypeManager.DefaultDataClasses.INTEGER, limit);
-        }
-        setDesiredType(limit.getRowLimit(), DataTypeManager.DefaultDataClasses.INTEGER, limit);
-    }
-    
-    public static void resolveImplicitTempGroup(TempMetadataAdapter metadata, GroupSymbol symbol, List symbols) 
-        throws TeiidComponentException, QueryResolverException {
-        
-        if (symbol.isImplicitTempGroupSymbol()) {
-            if (metadata.getMetadataStore().getTempElementElementIDs(symbol.getCanonicalName())==null) {
-                addTempGroup(metadata, symbol, symbols, true);
-            }
-            ResolverUtil.resolveGroup(symbol, metadata);
-        }
-    }
-
-    public static TempMetadataID addTempGroup(TempMetadataAdapter metadata,
-                                    GroupSymbol symbol,
-                                    List symbols, boolean tempTable) throws QueryResolverException {
-        HashSet<String> names = new HashSet<String>();
-        for (Iterator i = symbols.iterator(); i.hasNext();) {
-            SingleElementSymbol ses = (SingleElementSymbol)i.next();
-            if (!names.add(ses.getShortCanonicalName())) {
-                throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.duplicateName", symbol, ses.getShortName())); //$NON-NLS-1$
-            }
-        }
-        
-        if (tempTable) {
-            resolveNullLiterals(symbols);
-        }
-        TempMetadataStore store = metadata.getMetadataStore();
-        return store.addTempGroup(symbol.getName(), symbols, !tempTable, tempTable);
-    }
-    
-    public static TempMetadataID addTempTable(TempMetadataAdapter metadata,
-                                     GroupSymbol symbol,
-                                     List symbols) throws QueryResolverException {
-        return addTempGroup(metadata, symbol, symbols, true);
-    }
-
-    /** 
-     * Look for a null literal in the SELECT clause and set it's type to STRING.  This ensures that 
-     * the result set metadata retrieved for this query will be properly set to something other than
-     * the internal NullType.  Added for defect 15437.
-     * 
-     * @param select The select clause
-     * @since 4.2
-     */
-    public static void resolveNullLiterals(List symbols) {
-        for (int i = 0; i < symbols.size(); i++) {
-            SelectSymbol selectSymbol = (SelectSymbol) symbols.get(i);
-            
-            if (!(selectSymbol instanceof SingleElementSymbol)) {
-                continue;
-            }
-            
-            SingleElementSymbol symbol = (SingleElementSymbol)selectSymbol;
-            
-            if(!DataTypeManager.DefaultDataClasses.NULL.equals(symbol.getType()) && symbol.getType() != null) {
-                continue;
-            }
-            if(symbol instanceof AliasSymbol) {
-                symbol = ((AliasSymbol)symbol).getSymbol();
-            }
-                        
-            Class replacement = DataTypeManager.DefaultDataClasses.STRING;
-            
-            if(symbol instanceof ExpressionSymbol && !(symbol instanceof AggregateSymbol)) {
-                ExpressionSymbol exprSymbol = (ExpressionSymbol) symbol;
-                Expression expr = exprSymbol.getExpression();
-               	
-                if(expr instanceof Constant) {                	
-                    exprSymbol.setExpression(new Constant(null, replacement));
-                } else if (expr instanceof AbstractCaseExpression) {
-                    ((AbstractCaseExpression)expr).setType(replacement);
-                } else if (expr instanceof ScalarSubquery) {
-                    ((ScalarSubquery)expr).setType(replacement);                                        
-                } else {
-                	try {
-						ResolverUtil.setDesiredType(expr, replacement, symbol);
-					} catch (QueryResolverException e) {
-						//cannot happen
-					}
-                }
-            } else if(symbol instanceof ElementSymbol) {
-                ElementSymbol elementSymbol = (ElementSymbol)symbol;
-                Class elementType = elementSymbol.getType();
-                if(elementType != null && elementType.equals(DataTypeManager.DefaultDataClasses.NULL)) {
-                    elementSymbol.setType(replacement);
-                }
-            }
-        }
-    }
-    
-    /**
-     *  
-     * @param groupContext
-     * @param groups
-     * @param metadata
-     * @return the List of groups that match the given groupContext out of the supplied collection
-     * @throws TeiidComponentException
-     * @throws QueryMetadataException
-     */
-    public static List<GroupSymbol> findMatchingGroups(String groupContext,
-                            Collection<GroupSymbol> groups,
-                            QueryMetadataInterface metadata) throws TeiidComponentException,
-                                                            QueryMetadataException {
-
-        if (groups == null) {
-            return null;
-        }
-
-        LinkedList<GroupSymbol> matchedGroups = new LinkedList<GroupSymbol>();
-
-        if (groupContext == null) {
-            matchedGroups.addAll(groups);
-        } else {
-        	for (GroupSymbol group : groups) {
-                String fullName = group.getCanonicalName();
-                if (nameMatchesGroup(groupContext, matchedGroups, group, fullName)) {
-                    if (groupContext.length() == fullName.length()) {
-                        return matchedGroups;
-                    }
-                    continue;
-                }
-
-                // don't try to vdb qualify temp metadata
-                if (group.getMetadataID() instanceof TempMetadataID) {
-                    continue;
-                }
-
-                String actualVdbName = metadata.getVirtualDatabaseName();
-
-                if (actualVdbName != null) {
-                    fullName = actualVdbName.toUpperCase() + ElementSymbol.SEPARATOR + fullName;
-                    if (nameMatchesGroup(groupContext, matchedGroups, group, fullName)
-                        && groupContext.length() == fullName.length()) {
-                        return matchedGroups;
-                    }
-                }
-            }
-        }
-
-        return matchedGroups;
-    }
-
-    
-    private static boolean nameMatchesGroup(String groupContext,
-                                            String fullName) {
-        //if there is a name match, make sure that it is the full name or a proper qualifier
-        if (fullName.endsWith(groupContext)) {
-            int matchIndex = fullName.length() - groupContext.length();
-            if (matchIndex == 0 || fullName.charAt(matchIndex - 1) == '.') {
-                return true;
-            }
-        }
-        return false;
-    }
-    
-    private static boolean nameMatchesGroup(String groupContext,
-                                            LinkedList<GroupSymbol> matchedGroups,
-                                            GroupSymbol group,
-                                            String fullName) {
-        if (nameMatchesGroup(groupContext, fullName)) {
-            matchedGroups.add(group);
-            return true;
-        }
-        return false;
-    }
-
-	/**
-	 * Check the type of the (left) expression and the type of the single
-	 * projected symbol of the subquery.  If they are not the same, try to find
-	 * an implicit conversion from the former type to the latter type, and wrap
-	 * the left expression in that conversion function; otherwise throw an
-	 * Exception.
-	 * @param expression the Expression on one side of the predicate criteria
-	 * @param crit the SubqueryContainer containing the subquery Command of the other
-	 * side of the predicate criteria
-	 * @return implicit conversion Function, or null if none is necessary
-	 * @throws QueryResolverException if a conversion is necessary but none can
-	 * be found
-	 */
-	static Expression resolveSubqueryPredicateCriteria(Expression expression, SubqueryContainer crit, QueryMetadataInterface metadata)
-		throws QueryResolverException {
-	
-		// Check that type of the expression is same as the type of the
-		// single projected symbol of the subquery
-		Class exprType = expression.getType();
-		if(exprType == null) {
-	        throw new QueryResolverException("ERR.015.008.0030", QueryPlugin.Util.getString("ERR.015.008.0030", expression)); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-		String exprTypeName = DataTypeManager.getDataTypeName(exprType);
-	
-		Collection projectedSymbols = crit.getCommand().getProjectedSymbols();
-		if (projectedSymbols.size() != 1){
-	        throw new QueryResolverException("ERR.015.008.0032", QueryPlugin.Util.getString("ERR.015.008.0032", crit.getCommand())); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-		Class subqueryType = ((Expression)projectedSymbols.iterator().next()).getType();
-		String subqueryTypeName = DataTypeManager.getDataTypeName(subqueryType);
-		Expression result = null;
-	    try {
-	        result = convertExpression(expression, exprTypeName, subqueryTypeName, metadata);
-	    } catch (QueryResolverException qre) {
-	        throw new QueryResolverException(qre, "ERR.015.008.0033", QueryPlugin.Util.getString("ERR.015.008.0033", crit)); //$NON-NLS-1$ //$NON-NLS-2$
-	    }
-	    return result;
-	}
-
-	public static ResolvedLookup resolveLookup(Function lookup, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
-		Expression[] args = lookup.getArgs();
-		ResolvedLookup result = new ResolvedLookup();
-	    // Special code to handle setting return type of the lookup function to match the type of the return element
-	    if( !(args[0] instanceof Constant) || !(args[1] instanceof Constant) || !(args[2] instanceof Constant)) {
-		    throw new QueryResolverException("ERR.015.008.0063", QueryPlugin.Util.getString("ERR.015.008.0063")); //$NON-NLS-1$ //$NON-NLS-2$
-	    }
-        // If code table name in lookup function refers to temp group throw exception
-		GroupSymbol groupSym = new GroupSymbol((String) ((Constant)args[0]).getValue());
-		try {
-			groupSym.setMetadataID(metadata.getGroupID((String) ((Constant)args[0]).getValue()));
-			if (groupSym.getMetadataID() instanceof TempMetadataID) {
-				throw new QueryResolverException("ERR.015.008.0065", QueryPlugin.Util.getString("ERR.015.008.0065", ((Constant)args[0]).getValue())); //$NON-NLS-1$ //$NON-NLS-2$
-			}
-		} catch(QueryMetadataException e) {
-			throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", ((Constant)args[0]).getValue())); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-		result.setGroup(groupSym);
-		
-		List<GroupSymbol> groups = Arrays.asList(groupSym);
-		
-		String returnElementName = (String) ((Constant)args[0]).getValue() + "." + (String) ((Constant)args[1]).getValue(); //$NON-NLS-1$
-		ElementSymbol returnElement = new ElementSymbol(returnElementName);
-        try {
-            ResolverVisitor.resolveLanguageObject(returnElement, groups, metadata);
-        } catch(QueryMetadataException e) {
-            throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", returnElementName)); //$NON-NLS-1$ //$NON-NLS-2$
-        }
-		result.setReturnElement(returnElement);
-        
-        String keyElementName = (String) ((Constant)args[0]).getValue() + "." + (String) ((Constant)args[2]).getValue(); //$NON-NLS-1$
-        ElementSymbol keyElement = new ElementSymbol(keyElementName);
-        try {
-            ResolverVisitor.resolveLanguageObject(keyElement, groups, metadata);
-        } catch(QueryMetadataException e) {
-            throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", keyElementName)); //$NON-NLS-1$ //$NON-NLS-2$
-        }
-		result.setKeyElement(keyElement);
-		args[3] = convertExpression(args[3], DataTypeManager.getDataTypeName(keyElement.getType()), metadata);
-		return result;
-	}
-
-	private static QueryResolverException handleUnresolvedGroup(GroupSymbol symbol, String description) {
-		UnresolvedSymbolDescription usd = new UnresolvedSymbolDescription(symbol.toString(), description);
-	    QueryResolverException e = new QueryResolverException(usd.getDescription()+": "+usd.getSymbol()); //$NON-NLS-1$
-	    e.setUnresolvedSymbols(Arrays.asList(usd));
-	    return e;
-	}
-
-	public static void resolveGroup(GroupSymbol symbol, QueryMetadataInterface metadata)
-	    throws TeiidComponentException, QueryResolverException {
-	
-	    if (symbol.getMetadataID() != null){
-	        return;
-	    }
-	
-	    // determine the "metadataID" part of the symbol to look up
-	    String potentialID = symbol.getNonCorrelationName();
-	    
-	    String name = symbol.getName();
-	    String definition = symbol.getDefinition();
-	
-	    Object groupID = null;
-	    try {
-	        // get valid GroupID for possibleID - this may throw exceptions if group is invalid
-	        groupID = metadata.getGroupID(potentialID);
-	    } catch(QueryMetadataException e) {
-	        // didn't find this group ID
-	    } 
-	
-	    // If that didn't work, try to strip a vdb name from potentialID
-	    String vdbName = null;
-	    if(groupID == null) {
-	    	String[] parts = potentialID.split("\\.", 2); //$NON-NLS-1$
-	    	if (parts.length > 1 && parts[0].equalsIgnoreCase(metadata.getVirtualDatabaseName())) {
-	            try {
-	                groupID = metadata.getGroupID(parts[1]);
-	            } catch(QueryMetadataException e) {
-	                // ignore - just didn't find it
-	            } 
-	            if(groupID != null) {
-	            	potentialID = parts[1];
-	            	vdbName = parts[0];
-	            }
-	        }
-	    }
-	
-	    // the group could be partially qualified,  verify that this group exists
-	    // and there is only one group that matches the given partial name
-	    if(groupID == null) {
-	    	Collection groupNames = null;
-	    	try {
-	        	groupNames = metadata.getGroupsForPartialName(potentialID);
-	        } catch(QueryMetadataException e) {
-	            // ignore - just didn't find it
-	        } 
-	
-	        if(groupNames != null) {
-	            int matches = groupNames.size();
-	            if(matches == 1) {
-	            	potentialID = (String) groupNames.iterator().next();
-			        try {
-			            // get valid GroupID for possibleID - this may throw exceptions if group is invalid
-			            groupID = metadata.getGroupID(potentialID);
-			            //set group full name
-			            if(symbol.getDefinition() != null){
-			            	symbol.setDefinition(potentialID);
-			            }else{
-			            	symbol.setName(potentialID);
-			            }
-			        } catch(QueryMetadataException e) {
-			            // didn't find this group ID
-			        } 
-	            } else if(matches > 1) {
-	                throw handleUnresolvedGroup(symbol, QueryPlugin.Util.getString("ERR.015.008.0055")); //$NON-NLS-1$
-	            }
-	        }
-	    }
-	    
-	    if (groupID == null || metadata.isProcedure(groupID)) {
-		    //try procedure relational resolving
-	        try {
-	            StoredProcedureInfo storedProcedureInfo = metadata.getStoredProcedureInfoForProcedure(potentialID);
-	            symbol.setProcedure(true);
-	            groupID = storedProcedureInfo.getProcedureID();
-	        } catch(QueryMetadataException e) {
-	            // just ignore
-	        } 
-	    }
-	    
-	    if(groupID == null) {
-	        throw handleUnresolvedGroup(symbol, QueryPlugin.Util.getString("ERR.015.008.0056")); //$NON-NLS-1$
-	    }
-	    // set real metadata ID in the symbol
-	    symbol.setMetadataID(groupID);
-	    if(vdbName != null) {
-	        // reset name or definition to strip vdb name
-	        if(symbol.getDefinition() == null) {
-	            symbol.setName(potentialID);
-	        } else {
-	            symbol.setDefinition(potentialID);
-	        }
-	    }
-	    try {
-	        if (!symbol.isProcedure()) {
-	            symbol.setIsTempTable(metadata.isTemporaryTable(groupID));
-	        }
-	    } catch(QueryMetadataException e) {
-	        // should not come here
-	    } 
-	    
-	    symbol.setOutputDefinition(definition);
-	    symbol.setOutputName(name);
-	}
-	
-	public static void findKeyPreserved(Query query, Set<GroupSymbol> keyPreservingGroups, QueryMetadataInterface metadata)
-	throws TeiidComponentException, QueryMetadataException {
-		if (query.getFrom() == null) {
-			return;
-		}
-		if (query.getFrom().getClauses().size() == 1) {
-			findKeyPreserved((FromClause)query.getFrom().getClauses().get(0), keyPreservingGroups, metadata);
-			return;
-		}
-		//non-ansi join
-		Set<GroupSymbol> groups = new HashSet<GroupSymbol>(query.getFrom().getGroups());
-		for (GroupSymbol groupSymbol : groups) {
-			if (metadata.getUniqueKeysInGroup(groupSymbol.getMetadataID()).isEmpty()) {
-				return;
-			}
-		}
-		LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
-		LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
-		for (Criteria crit : Criteria.separateCriteriaByAnd(query.getCriteria())) {
-			if (!(crit instanceof CompareCriteria)) {
-				continue;
-			}
-			CompareCriteria cc = (CompareCriteria)crit;
-			if (cc.getOperator() != CompareCriteria.EQ) {
-				continue;
-			}
-			if (cc.getLeftExpression() instanceof ElementSymbol && cc.getRightExpression() instanceof ElementSymbol) {
-				ElementSymbol left = (ElementSymbol)cc.getLeftExpression();
-				ElementSymbol right = (ElementSymbol)cc.getRightExpression();
-				int compare = left.getGroupSymbol().compareTo(right.getGroupSymbol());
-				if (compare > 0) {
-					leftExpressions.add(left);
-					rightExpressions.add(right);
-				} else if (compare != 0) {
-					leftExpressions.add(right);
-					rightExpressions.add(left);
-				}
-			}
-		}
-		HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = createGroupMap(leftExpressions, rightExpressions);
-		HashSet<GroupSymbol> tempSet = new HashSet<GroupSymbol>();
-		HashSet<GroupSymbol> nonKeyPreserved = new HashSet<GroupSymbol>();
-		for (GroupSymbol group : groups) {
-			LinkedHashSet<GroupSymbol> visited = new LinkedHashSet<GroupSymbol>();
-			LinkedList<GroupSymbol> toVisit = new LinkedList<GroupSymbol>();
-			toVisit.add(group);
-			while (!toVisit.isEmpty()) {
-				GroupSymbol visiting = toVisit.removeLast();
-				if (!visited.add(visiting) || nonKeyPreserved.contains(visiting)) {
-					continue;
-				}
-				if (keyPreservingGroups.contains(visiting)) {
-					visited.addAll(groups);
-					break;
-				}
-				toVisit.addAll(findKeyPreserved(tempSet, Collections.singleton(visiting), crits, true, metadata, groups));
-				toVisit.addAll(findKeyPreserved(tempSet, Collections.singleton(visiting), crits, false, metadata, groups));
-			}
-			if (visited.containsAll(groups)) {
-				keyPreservingGroups.add(group);
-			} else {
-				nonKeyPreserved.add(group);
-			}
-		}
-	}
-		
-	public static void findKeyPreserved(FromClause clause, Set<GroupSymbol> keyPreservingGroups, QueryMetadataInterface metadata)
-	throws TeiidComponentException, QueryMetadataException {
-		if (clause instanceof UnaryFromClause) {
-			UnaryFromClause ufc = (UnaryFromClause)clause;
-		    
-			if (!metadata.getUniqueKeysInGroup(ufc.getGroup().getMetadataID()).isEmpty()) {
-				keyPreservingGroups.add(ufc.getGroup());
-			}
-		} 
-		if (clause instanceof JoinPredicate) {
-			JoinPredicate jp = (JoinPredicate)clause;
-			if (jp.getJoinType() == JoinType.JOIN_CROSS || jp.getJoinType() == JoinType.JOIN_FULL_OUTER) {
-				return;
-			}
-			HashSet<GroupSymbol> leftPk = new HashSet<GroupSymbol>();
-			findKeyPreserved(jp.getLeftClause(), leftPk, metadata);
-			HashSet<GroupSymbol> rightPk = new HashSet<GroupSymbol>();
-			findKeyPreserved(jp.getRightClause(), rightPk, metadata);
-			
-			if (leftPk.isEmpty() && rightPk.isEmpty()) {
-				return;
-			}
-			
-			HashSet<GroupSymbol> leftGroups = new HashSet<GroupSymbol>();
-			HashSet<GroupSymbol> rightGroups = new HashSet<GroupSymbol>();
-			jp.getLeftClause().collectGroups(leftGroups);
-			jp.getRightClause().collectGroups(rightGroups);
-			
-			LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
-			LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
-			RuleChooseJoinStrategy.separateCriteria(leftGroups, rightGroups, leftExpressions, rightExpressions, jp.getJoinCriteria(), new LinkedList<Criteria>());
-		    
-			HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = createGroupMap(leftExpressions, rightExpressions);
-			if (!leftPk.isEmpty() && (jp.getJoinType() == JoinType.JOIN_INNER || jp.getJoinType() == JoinType.JOIN_LEFT_OUTER)) {
-				findKeyPreserved(keyPreservingGroups, leftPk, crits, true, metadata, rightPk);
-			} 
-			if (!rightPk.isEmpty() && (jp.getJoinType() == JoinType.JOIN_INNER || jp.getJoinType() == JoinType.JOIN_RIGHT_OUTER)) {
-				findKeyPreserved(keyPreservingGroups, rightPk, crits, false, metadata, leftPk);
-			}
-		}
-	}
-
-	private static HashMap<List<GroupSymbol>, List<HashSet<Object>>> createGroupMap(
-			LinkedList<Expression> leftExpressions,
-			LinkedList<Expression> rightExpressions) {
-		HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = new HashMap<List<GroupSymbol>, List<HashSet<Object>>>();
-		
-		for (int i = 0; i < leftExpressions.size(); i++) {
-			Expression lexpr = leftExpressions.get(i);
-			Expression rexpr = rightExpressions.get(i);
-			if (!(lexpr instanceof ElementSymbol) || !(rexpr instanceof ElementSymbol)) {
-				continue;
-			}
-			ElementSymbol les = (ElementSymbol)lexpr;
-			ElementSymbol res = (ElementSymbol)rexpr;
-			List<GroupSymbol> tbls = Arrays.asList(les.getGroupSymbol(), res.getGroupSymbol());
-			List<HashSet<Object>> ids = crits.get(tbls);
-			if (ids == null) {
-				ids = Arrays.asList(new HashSet<Object>(), new HashSet<Object>());
-				crits.put(tbls, ids);
-			}
-			ids.get(0).add(les.getMetadataID());
-			ids.get(1).add(res.getMetadataID());
-		}
-		return crits;
-	}
-
-	static private HashSet<GroupSymbol> findKeyPreserved(Set<GroupSymbol> keyPreservingGroups,
-		Set<GroupSymbol> pk,
-		HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits, boolean left, QueryMetadataInterface metadata, Set<GroupSymbol> otherGroups)
-		throws TeiidComponentException, QueryMetadataException {
-		HashSet<GroupSymbol> result = new HashSet<GroupSymbol>();
-		for (GroupSymbol gs : pk) {
-			for (Map.Entry<List<GroupSymbol>, List<HashSet<Object>>> entry : crits.entrySet()) {
-				if (!entry.getKey().get(left?0:1).equals(gs) || !otherGroups.contains(entry.getKey().get(left?1:0))) {
-					continue;
-				}
-				if (RuleRaiseAccess.matchesForeignKey(metadata, entry.getValue().get(left?0:1), entry.getValue().get(left?1:0), gs, false)) {
-					keyPreservingGroups.add(gs);
-					result.add(entry.getKey().get(left?1:0));
-				}
-			}
-		}
-		return result;
-	}
-    
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java (from rev 2802, trunk/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,1096 @@
+/*
+ * 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.resolver.util;
+
+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.LinkedHashMap;
+import java.util.LinkedHashSet;
+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.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.UnresolvedSymbolDescription;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.TransformationException;
+import org.teiid.core.types.DataTypeManager.DefaultDataTypes;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.metadata.GroupInfo;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.StoredProcedureInfo;
+import org.teiid.query.metadata.SupportConstants;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.optimizer.relational.rules.RuleChooseJoinStrategy;
+import org.teiid.query.optimizer.relational.rules.RuleRaiseAccess;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.FromClause;
+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.OrderBy;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.symbol.AbstractCaseExpression;
+import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.AliasSymbol;
+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.SelectSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+
+
+/**
+ * Utilities used during resolution
+ */
+public class ResolverUtil {
+
+    public static class ResolvedLookup {
+		private GroupSymbol group;
+		private ElementSymbol keyElement;
+		private ElementSymbol returnElement;
+		
+		void setGroup(GroupSymbol group) {
+			this.group = group;
+		}
+		public GroupSymbol getGroup() {
+			return group;
+		}
+		void setKeyElement(ElementSymbol keyElement) {
+			this.keyElement = keyElement;
+		}
+		public ElementSymbol getKeyElement() {
+			return keyElement;
+		}
+		void setReturnElement(ElementSymbol returnElement) {
+			this.returnElement = returnElement;
+		}
+		public ElementSymbol getReturnElement() {
+			return returnElement;
+		}
+	}
+
+	// Can't construct
+    private ResolverUtil() {}
+
+    /*
+     *                        Type Conversion Utilities
+     */
+
+    /**
+     * Gets the most specific type to which all the given types have an implicit
+     * conversion. The method decides a common type as follows:
+     * <ul>
+     *   <li>If one or more of the given types is a candidate, then this method
+     *       will return the candidate that occurs first in the given array.
+     *       This is why the order of the names in the array is important. </li>
+     *   <li>Otherwise, if none of them is a candidate, this method will attempt
+     *       to find a common type to which all of them can be implicitly
+     *       converted.</li>
+     *   <li>Otherwise this method is unable to find a common type to which all
+     *       the given types can be implicitly converted, and therefore returns
+     *       a null.</li>
+     * </ul>
+     * @param typeNames an ordered array of unique type names.
+     * @return a type name to which all the given types can be converted
+     */
+    public static String getCommonType(String[] typeNames) {
+        if (typeNames == null || typeNames.length == 0) {
+            return null;
+        }
+        // If there is only one type, then simply return it
+        if (typeNames.length == 1) {
+            return typeNames[0];
+        }
+        // A type can be implicitly converted to itself, so we put the implicit
+        // conversions as well as the original type in the working list of
+        // conversions.
+        HashSet<String> commonConversions = new LinkedHashSet<String>();
+        commonConversions.add(typeNames[0]);
+        commonConversions.addAll(DataTypeManager.getImplicitConversions(typeNames[0]));
+        for (int i = 1; i < typeNames.length; i++ ) {
+            HashSet<String> conversions = new LinkedHashSet<String>(DataTypeManager.getImplicitConversions(typeNames[i]));
+            conversions.add(typeNames[i]);
+            // Equivalent to set intersection
+            commonConversions.retainAll(conversions);
+        }
+        if (commonConversions.isEmpty()) {
+            return null;
+        }
+        for (int i = 0; i < typeNames.length; i++) {
+            if (commonConversions.contains(typeNames[i])) {
+                return typeNames[i];
+            }
+        }
+    	commonConversions.remove(DefaultDataTypes.STRING);
+        commonConversions.remove(DefaultDataTypes.OBJECT);
+        if (!commonConversions.isEmpty()) {
+            return commonConversions.iterator().next(); 
+        }
+        return null;
+    }
+
+    /**
+     * Gets whether there exists an implicit conversion from the source type to
+     * the target type
+     * @param fromType
+     * @param toType
+     * @return true if there exists an implicit conversion from the
+     * <code>fromType</code> to the <code>toType</code>.
+     */
+    public static boolean canImplicitlyConvert(String fromType, String toType) {
+        if (fromType.equals(toType)) return true;
+        return DataTypeManager.isImplicitConversion(fromType, toType);
+    }
+
+    /**
+     * Replaces a sourceExpression with a conversion of the source expression
+     * to the target type. If the source type and target type are the same,
+     * this method does nothing.
+     * @param sourceExpression
+     * @param targetTypeName
+     * @return
+     * @throws QueryResolverException 
+     */
+    public static Expression convertExpression(Expression sourceExpression, String targetTypeName, QueryMetadataInterface metadata) throws QueryResolverException {
+        return convertExpression(sourceExpression,
+                                 DataTypeManager.getDataTypeName(sourceExpression.getType()),
+                                 targetTypeName, metadata);
+    }
+
+    /**
+     * Replaces a sourceExpression with a conversion of the source expression
+     * to the target type. If the source type and target type are the same,
+     * this method does nothing.
+     * @param sourceExpression
+     * @param sourceTypeName
+     * @param targetTypeName
+     * @return
+     * @throws QueryResolverException 
+     */
+    public static Expression convertExpression(Expression sourceExpression, String sourceTypeName, String targetTypeName, QueryMetadataInterface metadata) throws QueryResolverException {
+        if (sourceTypeName.equals(targetTypeName)) {
+            return sourceExpression;
+        }
+        
+        if(canImplicitlyConvert(sourceTypeName, targetTypeName) 
+                        || (sourceExpression instanceof Constant && convertConstant(sourceTypeName, targetTypeName, (Constant)sourceExpression) != null)) {
+            return getConversion(sourceExpression, sourceTypeName, targetTypeName, true, metadata.getFunctionLibrary());
+        }
+
+        //Expression is wrong type and can't convert
+        throw new QueryResolverException("ERR.015.008.0041", QueryPlugin.Util.getString("ERR.015.008.0041", new Object[] {targetTypeName, sourceExpression, sourceTypeName})); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    public static Constant convertConstant(String sourceTypeName,
+                                           String targetTypeName,
+                                           Constant constant) {
+        if (!DataTypeManager.isTransformable(sourceTypeName, targetTypeName)) {
+        	return null;
+        }
+
+        try {
+	        //try to get the converted constant, if this fails then it is not in a valid format
+	        Constant result = getProperlyTypedConstant(constant.getValue(), DataTypeManager.getDataTypeClass(targetTypeName));
+	        
+	        if (DataTypeManager.DefaultDataTypes.STRING.equals(sourceTypeName)) {
+	        	if (DataTypeManager.DefaultDataTypes.CHAR.equals(targetTypeName)) {
+	        		String value = (String)constant.getValue();
+	        		if (value != null && value.length() != 1) {
+	        			return null;
+	        		}
+	        	}
+	        	return result;
+	        }
+	        
+	        //for non-strings, ensure that the conversion is consistent
+	        if (!DataTypeManager.isTransformable(targetTypeName, sourceTypeName)) {
+	        	return null;
+	        }
+        
+	        if (!(constant.getValue() instanceof Comparable)) {
+	        	return null; //this is the case for xml constants
+	        }
+	        
+	        Constant reverse = getProperlyTypedConstant(result.getValue(), constant.getType());
+	        
+	        if (((Comparable)constant.getValue()).compareTo(reverse.getValue()) == 0) {
+	            return result;
+	        }
+        } catch (QueryResolverException e) {
+        	
+        }
+            
+        return null;
+    }
+
+    public static Function getConversion(Expression sourceExpression,
+                                            String sourceTypeName,
+                                            String targetTypeName,
+                                            boolean implicit, FunctionLibrary library) {
+        Class<?> srcType = DataTypeManager.getDataTypeClass(sourceTypeName);
+
+        FunctionDescriptor fd = library.findTypedConversionFunction(srcType, DataTypeManager.getDataTypeClass(targetTypeName));
+
+        Function conversion = new Function(fd.getName(), new Expression[] { sourceExpression, new Constant(targetTypeName) });
+        conversion.setType(DataTypeManager.getDataTypeClass(targetTypeName));
+        conversion.setFunctionDescriptor(fd);
+        if (implicit) {
+        	conversion.makeImplicit();
+        }
+
+        return conversion;
+    }
+
+    /**
+     * Utility to set the type of an expression if it is a Reference and has a null type.
+     * @param expression the expression to test
+     * @param targetType the target type, if the expression's type is null.
+     * @throws QueryResolverException if unable to set the reference type to the target type.
+     */
+    public static void setDesiredType(Expression expression, Class<?> targetType, LanguageObject surroundingExpression) throws QueryResolverException {
+        if (expression instanceof Reference) {
+        	Reference ref = (Reference)expression;
+        	if (ref.isPositional() && ref.getType() == null) {
+	        	if (targetType == null) {
+	        		throw new QueryResolverException("ERR.015.008.0026", QueryPlugin.Util.getString("ERR.015.008.0026", surroundingExpression)); //$NON-NLS-1$ //$NON-NLS-2$
+	        	}
+	            ref.setType(targetType);
+        	}
+        } else if (expression instanceof Function) {
+        	Function f = (Function)expression;
+        	if (f.getType() == null) {
+	        	f.setType(targetType);
+        	}
+        }
+    }
+    
+	/**
+	 * Attempt to resolve the order by throws QueryResolverException if the
+	 * symbol is not of SingleElementSymbol type
+	 * 
+	 * @param orderBy
+	 * @param fromClauseGroups
+	 *            groups of the FROM clause of the query (for resolving
+	 *            ambiguous unqualified element names), or empty List if a Set
+	 *            Query Order By is being resolved
+	 * @param knownElements
+	 *            resolved elements from SELECT clause, which are only ones
+	 *            allowed to be in ORDER BY
+	 * @param metadata
+	 *            QueryMetadataInterface
+	 */
+    public static void resolveOrderBy(OrderBy orderBy, QueryCommand command, QueryMetadataInterface metadata)
+        throws QueryResolverException, QueryMetadataException, TeiidComponentException {
+
+    	List<SingleElementSymbol> knownElements = command.getProjectedQuery().getSelect().getProjectedSymbols();
+    	
+    	boolean isSimpleQuery = false;
+    	List fromClauseGroups = Collections.emptyList();
+        
+        if (command instanceof Query) {
+        	Query query = (Query)command;
+        	isSimpleQuery = !query.getSelect().isDistinct() && !query.hasAggregates();
+        	if (query.getFrom() != null) {
+        		fromClauseGroups = query.getFrom().getGroups();
+        	}
+        }
+    	
+        // Cached state, if needed
+        String[] knownShortNames = new String[knownElements.size()];
+        List<Expression> expressions = new ArrayList<Expression>(knownElements.size());
+
+        for(int i=0; i<knownElements.size(); i++) {
+            SingleElementSymbol knownSymbol = knownElements.get(i);
+            expressions.add(SymbolMap.getExpression(knownSymbol));
+            if (knownSymbol instanceof ExpressionSymbol) {
+                continue;
+            }
+            
+            String name = knownSymbol.getShortName();
+            
+            knownShortNames[i] = name;
+        }
+
+        for (int i = 0; i < orderBy.getVariableCount(); i++) {
+        	SingleElementSymbol sortKey = orderBy.getVariable(i);
+        	if (sortKey instanceof ElementSymbol) {
+        		ElementSymbol symbol = (ElementSymbol)sortKey;
+        		String groupPart = metadata.getGroupName(symbol.getName());
+        		String symbolName = symbol.getName();
+        		String shortName = symbol.getShortName();
+        		if (groupPart == null) {
+        			int position = -1;
+    				SingleElementSymbol matchedSymbol = null;
+    				// walk the SELECT col short names, looking for a match on the current ORDER BY 'short name'
+    				for(int j=0; j<knownShortNames.length; j++) {
+    					if( !shortName.equalsIgnoreCase( knownShortNames[j] )) {
+    						continue;
+    					}
+    			        // if we already have a matched symbol, matching again here means it is duplicate/ambiguous
+    			        if(matchedSymbol != null) {
+    			        	if (!matchedSymbol.equals(knownElements.get(j))) {
+    			        		throw new QueryResolverException("ERR.015.008.0042", QueryPlugin.Util.getString("ERR.015.008.0042", symbolName)); //$NON-NLS-1$ //$NON-NLS-2$
+    			        	}
+    			        	continue;
+    			        }
+    			        matchedSymbol = knownElements.get(j);
+    			        position = j;
+    				}
+    				if (matchedSymbol != null) {
+    				    TempMetadataID tempMetadataID = new TempMetadataID(symbol.getName(), matchedSymbol.getType());
+    				    symbol.setMetadataID(tempMetadataID);
+    				    symbol.setType(matchedSymbol.getType());
+    				}
+                    if (position != -1) {
+                        orderBy.setExpressionPosition(i, position);
+                        continue;
+                    }
+        		}
+        	} else if (sortKey instanceof ExpressionSymbol) {
+        		// check for legacy positional
+    			ExpressionSymbol es = (ExpressionSymbol)sortKey;
+        		if (es.getExpression() instanceof Constant) {
+            		Constant c = (Constant)es.getExpression();
+        		    int elementOrder = Integer.valueOf(c.getValue().toString()).intValue();
+        		    // adjust for the 1 based index.
+        		    if (elementOrder > knownElements.size() || elementOrder < 1) {
+            		    throw new QueryResolverException(QueryPlugin.Util.getString("SQLParser.non_position_constant", c)); //$NON-NLS-1$
+        		    }
+        		    orderBy.setExpressionPosition(i, elementOrder - 1);
+        		    continue;
+        		}
+        	}
+        	//handle order by expressions        	
+        	if (command instanceof SetQuery) {
+    			throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.setquery_order_expression", sortKey)); //$NON-NLS-1$	 
+    		}
+        	for (ElementSymbol symbol : ElementCollectorVisitor.getElements(sortKey, false)) {
+        		try {
+        	    	ResolverVisitor.resolveLanguageObject(symbol, fromClauseGroups, command.getExternalGroupContexts(), metadata);
+        	    } catch(QueryResolverException e) {
+        	    	throw new QueryResolverException(e, "ERR.015.008.0043", QueryPlugin.Util.getString("ERR.015.008.0043", symbol.getName()) );//$NON-NLS-1$ //$NON-NLS-2$
+        	    } 
+			}
+            ResolverVisitor.resolveLanguageObject(sortKey, metadata);
+            
+            int index = expressions.indexOf(SymbolMap.getExpression(sortKey));
+            if (index == -1 && !isSimpleQuery) {
+    	        throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.invalid_unrelated", sortKey)); //$NON-NLS-1$
+        	}
+        	orderBy.setExpressionPosition(i, index);
+        }
+    }
+    
+    /** 
+     * Get the default value for the parameter, which could be null
+     * if the parameter is set to NULLABLE.  If no default is available,
+     * a QueryResolverException will be thrown.
+     * 
+     * @param symbol ElementSymbol retrieved from metadata, fully-resolved
+     * @param metadata QueryMetadataInterface
+     * @return expr param (if it is non-null) or default value (if there is one)
+     * or null Constant (if parameter is optional and therefore allows this)
+     * @throws QueryResolverException if expr is null, parameter is required and no
+     * default value is defined
+     * @throws QueryMetadataException for error retrieving metadata
+     * @throws TeiidComponentException
+     * @since 4.3
+     */
+	public static Expression getDefault(ElementSymbol symbol, QueryMetadataInterface metadata) throws TeiidComponentException, QueryMetadataException, QueryResolverException {
+        //Check if there is a default value, if so use it
+		Object mid = symbol.getMetadataID();
+    	Class type = symbol.getType();
+    	String name = symbol.getCanonicalName();
+		
+        Object defaultValue = metadata.getDefaultValue(mid);
+        
+        if (defaultValue == null && !metadata.elementSupports(mid, SupportConstants.Element.NULL)) {
+            throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.required_param", name)); //$NON-NLS-1$
+        }
+        
+        return getProperlyTypedConstant(defaultValue, type);
+	}    
+    
+    /** 
+     * Construct a Constant with proper type, given the String default
+     * value for the parameter and the parameter type.  Throw a
+     * QueryResolverException if the String can't be transformed.
+     * @param defaultValue, either null or a String
+     * @param parameterType modeled type of parameter (MetaMatrix runtime type)
+     * @return Constant with proper type and default value Object of proper Class.  Will
+     * be null Constant if defaultValue is null.
+     * @throws QueryResolverException if TransformationException is encountered
+     * @since 4.3
+     */
+    private static Constant getProperlyTypedConstant(Object defaultValue,
+                                                Class parameterType)
+    throws QueryResolverException{
+        try {
+            Object newValue = DataTypeManager.transformValue(defaultValue, parameterType);
+            return new Constant(newValue, parameterType);
+        } catch (TransformationException e) {
+            throw new QueryResolverException(e, QueryPlugin.Util.getString("ResolverUtil.error_converting_value_type", defaultValue, defaultValue.getClass(), parameterType)); //$NON-NLS-1$
+        }
+    }
+
+    /**
+     * Returns the resolved elements in the given group.  This method has the side effect of caching the resolved elements on the group object.
+     * The resolved elements may not contain non-selectable columns depending on the metadata first used for resolving.
+     * 
+     */
+    public static List<ElementSymbol> resolveElementsInGroup(GroupSymbol group, QueryMetadataInterface metadata)
+    throws QueryMetadataException, TeiidComponentException {
+        return new ArrayList<ElementSymbol>(getGroupInfo(group, metadata).getSymbolList());
+    }
+    
+	static GroupInfo getGroupInfo(GroupSymbol group,
+			QueryMetadataInterface metadata)
+			throws TeiidComponentException, QueryMetadataException {
+		String key = GroupInfo.CACHE_PREFIX + group.getCanonicalName();
+		GroupInfo groupInfo = (GroupInfo)metadata.getFromMetadataCache(group.getMetadataID(), key);
+    	
+        if (groupInfo == null) {
+        	group = group.clone();
+            // get all elements from the metadata
+            List elementIDs = metadata.getElementIDsInGroupID(group.getMetadataID());
+
+    		LinkedHashMap<Object, ElementSymbol> symbols = new LinkedHashMap<Object, ElementSymbol>(elementIDs.size());
+                        
+            boolean groupIsAliased = group.getDefinition() != null;
+            
+            for (Object elementID : elementIDs) {
+                String elementName = metadata.getFullName(elementID);
+                String fullName = elementName;
+    			// This is only really needed if the group is an ALIAS.  Doing the check outside the loop
+                // and NOT doing unnecessary work if Aliased group.
+                if(groupIsAliased) {
+                	String shortName = metadata.getShortElementName(elementName);
+                    fullName = metadata.getFullElementName(group.getName(), shortName);
+                }
+
+                // Form an element symbol from the ID
+                ElementSymbol element = new ElementSymbol(fullName);
+                element.setGroupSymbol(group);
+                element.setMetadataID(elementID);
+                element.setType( DataTypeManager.getDataTypeClass(metadata.getElementType(element.getMetadataID())) );
+
+                symbols.put(elementID, element);
+            }
+            groupInfo = new GroupInfo(symbols);
+            metadata.addToMetadataCache(group.getMetadataID(), key, groupInfo);
+        }
+		return groupInfo;
+	}
+    
+    /**
+     * When access patterns are flattened, they are an approximation the user
+     * may need to enter as criteria.
+     *  
+     * @param metadata
+     * @param groups
+     * @param flatten
+     * @return
+     * @throws TeiidComponentException
+     * @throws QueryMetadataException
+     */
+	public static List getAccessPatternElementsInGroups(final QueryMetadataInterface metadata, Collection groups, boolean flatten) throws TeiidComponentException, QueryMetadataException {
+		List accessPatterns = null;
+		Iterator i = groups.iterator();
+		while (i.hasNext()){
+		    
+		    GroupSymbol group = (GroupSymbol)i.next();
+		    
+		    //Check this group for access pattern(s).
+		    Collection accessPatternIDs = metadata.getAccessPatternsInGroup(group.getMetadataID());
+		    if (accessPatternIDs != null && accessPatternIDs.size() > 0){
+		        Iterator j = accessPatternIDs.iterator();
+		        if (accessPatterns == null){
+		            accessPatterns = new ArrayList();
+		        }
+		        while (j.hasNext()) {
+		        	List elements = metadata.getElementIDsInAccessPattern(j.next());
+		        	GroupInfo groupInfo = getGroupInfo(group, metadata);
+		        	List result = new ArrayList(elements.size());
+		        	for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
+		    			Object id = iterator.next();
+		    			ElementSymbol symbol = groupInfo.getSymbol(id);
+		    			assert symbol != null;
+		    			result.add(symbol);
+		    		}
+		        	if (flatten) {
+		        		accessPatterns.addAll(result);
+		        	} else {
+		        		accessPatterns.add(new AccessPattern(result));
+		        	}
+		        }
+		    }
+		}
+                
+		return accessPatterns;
+	}
+
+    public static void resolveLimit(Limit limit) throws QueryResolverException {
+        if (limit.getOffset() != null) {
+            setDesiredType(limit.getOffset(), DataTypeManager.DefaultDataClasses.INTEGER, limit);
+        }
+        setDesiredType(limit.getRowLimit(), DataTypeManager.DefaultDataClasses.INTEGER, limit);
+    }
+    
+    public static void resolveImplicitTempGroup(TempMetadataAdapter metadata, GroupSymbol symbol, List symbols) 
+        throws TeiidComponentException, QueryResolverException {
+        
+        if (symbol.isImplicitTempGroupSymbol()) {
+            if (metadata.getMetadataStore().getTempElementElementIDs(symbol.getCanonicalName())==null) {
+                addTempGroup(metadata, symbol, symbols, true);
+            }
+            ResolverUtil.resolveGroup(symbol, metadata);
+        }
+    }
+
+    public static TempMetadataID addTempGroup(TempMetadataAdapter metadata,
+                                    GroupSymbol symbol,
+                                    List symbols, boolean tempTable) throws QueryResolverException {
+        HashSet<String> names = new HashSet<String>();
+        for (Iterator i = symbols.iterator(); i.hasNext();) {
+            SingleElementSymbol ses = (SingleElementSymbol)i.next();
+            if (!names.add(ses.getShortCanonicalName())) {
+                throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.duplicateName", symbol, ses.getShortName())); //$NON-NLS-1$
+            }
+        }
+        
+        if (tempTable) {
+            resolveNullLiterals(symbols);
+        }
+        TempMetadataStore store = metadata.getMetadataStore();
+        return store.addTempGroup(symbol.getName(), symbols, !tempTable, tempTable);
+    }
+    
+    public static TempMetadataID addTempTable(TempMetadataAdapter metadata,
+                                     GroupSymbol symbol,
+                                     List symbols) throws QueryResolverException {
+        return addTempGroup(metadata, symbol, symbols, true);
+    }
+
+    /** 
+     * Look for a null literal in the SELECT clause and set it's type to STRING.  This ensures that 
+     * the result set metadata retrieved for this query will be properly set to something other than
+     * the internal NullType.  Added for defect 15437.
+     * 
+     * @param select The select clause
+     * @since 4.2
+     */
+    public static void resolveNullLiterals(List symbols) {
+        for (int i = 0; i < symbols.size(); i++) {
+            SelectSymbol selectSymbol = (SelectSymbol) symbols.get(i);
+            
+            if (!(selectSymbol instanceof SingleElementSymbol)) {
+                continue;
+            }
+            
+            SingleElementSymbol symbol = (SingleElementSymbol)selectSymbol;
+            
+            if(!DataTypeManager.DefaultDataClasses.NULL.equals(symbol.getType()) && symbol.getType() != null) {
+                continue;
+            }
+            if(symbol instanceof AliasSymbol) {
+                symbol = ((AliasSymbol)symbol).getSymbol();
+            }
+                        
+            Class replacement = DataTypeManager.DefaultDataClasses.STRING;
+            
+            if(symbol instanceof ExpressionSymbol && !(symbol instanceof AggregateSymbol)) {
+                ExpressionSymbol exprSymbol = (ExpressionSymbol) symbol;
+                Expression expr = exprSymbol.getExpression();
+               	
+                if(expr instanceof Constant) {                	
+                    exprSymbol.setExpression(new Constant(null, replacement));
+                } else if (expr instanceof AbstractCaseExpression) {
+                    ((AbstractCaseExpression)expr).setType(replacement);
+                } else if (expr instanceof ScalarSubquery) {
+                    ((ScalarSubquery)expr).setType(replacement);                                        
+                } else {
+                	try {
+						ResolverUtil.setDesiredType(expr, replacement, symbol);
+					} catch (QueryResolverException e) {
+						//cannot happen
+					}
+                }
+            } else if(symbol instanceof ElementSymbol) {
+                ElementSymbol elementSymbol = (ElementSymbol)symbol;
+                Class elementType = elementSymbol.getType();
+                if(elementType != null && elementType.equals(DataTypeManager.DefaultDataClasses.NULL)) {
+                    elementSymbol.setType(replacement);
+                }
+            }
+        }
+    }
+    
+    /**
+     *  
+     * @param groupContext
+     * @param groups
+     * @param metadata
+     * @return the List of groups that match the given groupContext out of the supplied collection
+     * @throws TeiidComponentException
+     * @throws QueryMetadataException
+     */
+    public static List<GroupSymbol> findMatchingGroups(String groupContext,
+                            Collection<GroupSymbol> groups,
+                            QueryMetadataInterface metadata) throws TeiidComponentException,
+                                                            QueryMetadataException {
+
+        if (groups == null) {
+            return null;
+        }
+
+        LinkedList<GroupSymbol> matchedGroups = new LinkedList<GroupSymbol>();
+
+        if (groupContext == null) {
+            matchedGroups.addAll(groups);
+        } else {
+        	for (GroupSymbol group : groups) {
+                String fullName = group.getCanonicalName();
+                if (nameMatchesGroup(groupContext, matchedGroups, group, fullName)) {
+                    if (groupContext.length() == fullName.length()) {
+                        return matchedGroups;
+                    }
+                    continue;
+                }
+
+                // don't try to vdb qualify temp metadata
+                if (group.getMetadataID() instanceof TempMetadataID) {
+                    continue;
+                }
+
+                String actualVdbName = metadata.getVirtualDatabaseName();
+
+                if (actualVdbName != null) {
+                    fullName = actualVdbName.toUpperCase() + ElementSymbol.SEPARATOR + fullName;
+                    if (nameMatchesGroup(groupContext, matchedGroups, group, fullName)
+                        && groupContext.length() == fullName.length()) {
+                        return matchedGroups;
+                    }
+                }
+            }
+        }
+
+        return matchedGroups;
+    }
+
+    
+    private static boolean nameMatchesGroup(String groupContext,
+                                            String fullName) {
+        //if there is a name match, make sure that it is the full name or a proper qualifier
+        if (fullName.endsWith(groupContext)) {
+            int matchIndex = fullName.length() - groupContext.length();
+            if (matchIndex == 0 || fullName.charAt(matchIndex - 1) == '.') {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    private static boolean nameMatchesGroup(String groupContext,
+                                            LinkedList<GroupSymbol> matchedGroups,
+                                            GroupSymbol group,
+                                            String fullName) {
+        if (nameMatchesGroup(groupContext, fullName)) {
+            matchedGroups.add(group);
+            return true;
+        }
+        return false;
+    }
+
+	/**
+	 * Check the type of the (left) expression and the type of the single
+	 * projected symbol of the subquery.  If they are not the same, try to find
+	 * an implicit conversion from the former type to the latter type, and wrap
+	 * the left expression in that conversion function; otherwise throw an
+	 * Exception.
+	 * @param expression the Expression on one side of the predicate criteria
+	 * @param crit the SubqueryContainer containing the subquery Command of the other
+	 * side of the predicate criteria
+	 * @return implicit conversion Function, or null if none is necessary
+	 * @throws QueryResolverException if a conversion is necessary but none can
+	 * be found
+	 */
+	static Expression resolveSubqueryPredicateCriteria(Expression expression, SubqueryContainer crit, QueryMetadataInterface metadata)
+		throws QueryResolverException {
+	
+		// Check that type of the expression is same as the type of the
+		// single projected symbol of the subquery
+		Class exprType = expression.getType();
+		if(exprType == null) {
+	        throw new QueryResolverException("ERR.015.008.0030", QueryPlugin.Util.getString("ERR.015.008.0030", expression)); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+		String exprTypeName = DataTypeManager.getDataTypeName(exprType);
+	
+		Collection projectedSymbols = crit.getCommand().getProjectedSymbols();
+		if (projectedSymbols.size() != 1){
+	        throw new QueryResolverException("ERR.015.008.0032", QueryPlugin.Util.getString("ERR.015.008.0032", crit.getCommand())); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+		Class subqueryType = ((Expression)projectedSymbols.iterator().next()).getType();
+		String subqueryTypeName = DataTypeManager.getDataTypeName(subqueryType);
+		Expression result = null;
+	    try {
+	        result = convertExpression(expression, exprTypeName, subqueryTypeName, metadata);
+	    } catch (QueryResolverException qre) {
+	        throw new QueryResolverException(qre, "ERR.015.008.0033", QueryPlugin.Util.getString("ERR.015.008.0033", crit)); //$NON-NLS-1$ //$NON-NLS-2$
+	    }
+	    return result;
+	}
+
+	public static ResolvedLookup resolveLookup(Function lookup, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
+		Expression[] args = lookup.getArgs();
+		ResolvedLookup result = new ResolvedLookup();
+	    // Special code to handle setting return type of the lookup function to match the type of the return element
+	    if( !(args[0] instanceof Constant) || !(args[1] instanceof Constant) || !(args[2] instanceof Constant)) {
+		    throw new QueryResolverException("ERR.015.008.0063", QueryPlugin.Util.getString("ERR.015.008.0063")); //$NON-NLS-1$ //$NON-NLS-2$
+	    }
+        // If code table name in lookup function refers to temp group throw exception
+		GroupSymbol groupSym = new GroupSymbol((String) ((Constant)args[0]).getValue());
+		try {
+			groupSym.setMetadataID(metadata.getGroupID((String) ((Constant)args[0]).getValue()));
+			if (groupSym.getMetadataID() instanceof TempMetadataID) {
+				throw new QueryResolverException("ERR.015.008.0065", QueryPlugin.Util.getString("ERR.015.008.0065", ((Constant)args[0]).getValue())); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		} catch(QueryMetadataException e) {
+			throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", ((Constant)args[0]).getValue())); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+		result.setGroup(groupSym);
+		
+		List<GroupSymbol> groups = Arrays.asList(groupSym);
+		
+		String returnElementName = (String) ((Constant)args[0]).getValue() + "." + (String) ((Constant)args[1]).getValue(); //$NON-NLS-1$
+		ElementSymbol returnElement = new ElementSymbol(returnElementName);
+        try {
+            ResolverVisitor.resolveLanguageObject(returnElement, groups, metadata);
+        } catch(QueryMetadataException e) {
+            throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", returnElementName)); //$NON-NLS-1$ //$NON-NLS-2$
+        }
+		result.setReturnElement(returnElement);
+        
+        String keyElementName = (String) ((Constant)args[0]).getValue() + "." + (String) ((Constant)args[2]).getValue(); //$NON-NLS-1$
+        ElementSymbol keyElement = new ElementSymbol(keyElementName);
+        try {
+            ResolverVisitor.resolveLanguageObject(keyElement, groups, metadata);
+        } catch(QueryMetadataException e) {
+            throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", keyElementName)); //$NON-NLS-1$ //$NON-NLS-2$
+        }
+		result.setKeyElement(keyElement);
+		args[3] = convertExpression(args[3], DataTypeManager.getDataTypeName(keyElement.getType()), metadata);
+		return result;
+	}
+
+	private static QueryResolverException handleUnresolvedGroup(GroupSymbol symbol, String description) {
+		UnresolvedSymbolDescription usd = new UnresolvedSymbolDescription(symbol.toString(), description);
+	    QueryResolverException e = new QueryResolverException(usd.getDescription()+": "+usd.getSymbol()); //$NON-NLS-1$
+	    e.setUnresolvedSymbols(Arrays.asList(usd));
+	    return e;
+	}
+
+	public static void resolveGroup(GroupSymbol symbol, QueryMetadataInterface metadata)
+	    throws TeiidComponentException, QueryResolverException {
+	
+	    if (symbol.getMetadataID() != null){
+	        return;
+	    }
+	
+	    // determine the "metadataID" part of the symbol to look up
+	    String potentialID = symbol.getNonCorrelationName();
+	    
+	    String name = symbol.getName();
+	    String definition = symbol.getDefinition();
+	
+	    Object groupID = null;
+	    try {
+	        // get valid GroupID for possibleID - this may throw exceptions if group is invalid
+	        groupID = metadata.getGroupID(potentialID);
+	    } catch(QueryMetadataException e) {
+	        // didn't find this group ID
+	    } 
+	
+	    // If that didn't work, try to strip a vdb name from potentialID
+	    String vdbName = null;
+	    if(groupID == null) {
+	    	String[] parts = potentialID.split("\\.", 2); //$NON-NLS-1$
+	    	if (parts.length > 1 && parts[0].equalsIgnoreCase(metadata.getVirtualDatabaseName())) {
+	            try {
+	                groupID = metadata.getGroupID(parts[1]);
+	            } catch(QueryMetadataException e) {
+	                // ignore - just didn't find it
+	            } 
+	            if(groupID != null) {
+	            	potentialID = parts[1];
+	            	vdbName = parts[0];
+	            }
+	        }
+	    }
+	
+	    // the group could be partially qualified,  verify that this group exists
+	    // and there is only one group that matches the given partial name
+	    if(groupID == null) {
+	    	Collection groupNames = null;
+	    	try {
+	        	groupNames = metadata.getGroupsForPartialName(potentialID);
+	        } catch(QueryMetadataException e) {
+	            // ignore - just didn't find it
+	        } 
+	
+	        if(groupNames != null) {
+	            int matches = groupNames.size();
+	            if(matches == 1) {
+	            	potentialID = (String) groupNames.iterator().next();
+			        try {
+			            // get valid GroupID for possibleID - this may throw exceptions if group is invalid
+			            groupID = metadata.getGroupID(potentialID);
+			            //set group full name
+			            if(symbol.getDefinition() != null){
+			            	symbol.setDefinition(potentialID);
+			            }else{
+			            	symbol.setName(potentialID);
+			            }
+			        } catch(QueryMetadataException e) {
+			            // didn't find this group ID
+			        } 
+	            } else if(matches > 1) {
+	                throw handleUnresolvedGroup(symbol, QueryPlugin.Util.getString("ERR.015.008.0055")); //$NON-NLS-1$
+	            }
+	        }
+	    }
+	    
+	    if (groupID == null || metadata.isProcedure(groupID)) {
+		    //try procedure relational resolving
+	        try {
+	            StoredProcedureInfo storedProcedureInfo = metadata.getStoredProcedureInfoForProcedure(potentialID);
+	            symbol.setProcedure(true);
+	            groupID = storedProcedureInfo.getProcedureID();
+	        } catch(QueryMetadataException e) {
+	            // just ignore
+	        } 
+	    }
+	    
+	    if(groupID == null) {
+	        throw handleUnresolvedGroup(symbol, QueryPlugin.Util.getString("ERR.015.008.0056")); //$NON-NLS-1$
+	    }
+	    // set real metadata ID in the symbol
+	    symbol.setMetadataID(groupID);
+	    if(vdbName != null) {
+	        // reset name or definition to strip vdb name
+	        if(symbol.getDefinition() == null) {
+	            symbol.setName(potentialID);
+	        } else {
+	            symbol.setDefinition(potentialID);
+	        }
+	    }
+	    try {
+	        if (!symbol.isProcedure()) {
+	            symbol.setIsTempTable(metadata.isTemporaryTable(groupID));
+	        }
+	    } catch(QueryMetadataException e) {
+	        // should not come here
+	    } 
+	    
+	    symbol.setOutputDefinition(definition);
+	    symbol.setOutputName(name);
+	}
+	
+	public static void findKeyPreserved(Query query, Set<GroupSymbol> keyPreservingGroups, QueryMetadataInterface metadata)
+	throws TeiidComponentException, QueryMetadataException {
+		if (query.getFrom() == null) {
+			return;
+		}
+		if (query.getFrom().getClauses().size() == 1) {
+			findKeyPreserved((FromClause)query.getFrom().getClauses().get(0), keyPreservingGroups, metadata);
+			return;
+		}
+		//non-ansi join
+		Set<GroupSymbol> groups = new HashSet<GroupSymbol>(query.getFrom().getGroups());
+		for (GroupSymbol groupSymbol : groups) {
+			if (metadata.getUniqueKeysInGroup(groupSymbol.getMetadataID()).isEmpty()) {
+				return;
+			}
+		}
+		LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
+		LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
+		for (Criteria crit : Criteria.separateCriteriaByAnd(query.getCriteria())) {
+			if (!(crit instanceof CompareCriteria)) {
+				continue;
+			}
+			CompareCriteria cc = (CompareCriteria)crit;
+			if (cc.getOperator() != CompareCriteria.EQ) {
+				continue;
+			}
+			if (cc.getLeftExpression() instanceof ElementSymbol && cc.getRightExpression() instanceof ElementSymbol) {
+				ElementSymbol left = (ElementSymbol)cc.getLeftExpression();
+				ElementSymbol right = (ElementSymbol)cc.getRightExpression();
+				int compare = left.getGroupSymbol().compareTo(right.getGroupSymbol());
+				if (compare > 0) {
+					leftExpressions.add(left);
+					rightExpressions.add(right);
+				} else if (compare != 0) {
+					leftExpressions.add(right);
+					rightExpressions.add(left);
+				}
+			}
+		}
+		HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = createGroupMap(leftExpressions, rightExpressions);
+		HashSet<GroupSymbol> tempSet = new HashSet<GroupSymbol>();
+		HashSet<GroupSymbol> nonKeyPreserved = new HashSet<GroupSymbol>();
+		for (GroupSymbol group : groups) {
+			LinkedHashSet<GroupSymbol> visited = new LinkedHashSet<GroupSymbol>();
+			LinkedList<GroupSymbol> toVisit = new LinkedList<GroupSymbol>();
+			toVisit.add(group);
+			while (!toVisit.isEmpty()) {
+				GroupSymbol visiting = toVisit.removeLast();
+				if (!visited.add(visiting) || nonKeyPreserved.contains(visiting)) {
+					continue;
+				}
+				if (keyPreservingGroups.contains(visiting)) {
+					visited.addAll(groups);
+					break;
+				}
+				toVisit.addAll(findKeyPreserved(tempSet, Collections.singleton(visiting), crits, true, metadata, groups));
+				toVisit.addAll(findKeyPreserved(tempSet, Collections.singleton(visiting), crits, false, metadata, groups));
+			}
+			if (visited.containsAll(groups)) {
+				keyPreservingGroups.add(group);
+			} else {
+				nonKeyPreserved.add(group);
+			}
+		}
+	}
+		
+	public static void findKeyPreserved(FromClause clause, Set<GroupSymbol> keyPreservingGroups, QueryMetadataInterface metadata)
+	throws TeiidComponentException, QueryMetadataException {
+		if (clause instanceof UnaryFromClause) {
+			UnaryFromClause ufc = (UnaryFromClause)clause;
+		    
+			if (!metadata.getUniqueKeysInGroup(ufc.getGroup().getMetadataID()).isEmpty()) {
+				keyPreservingGroups.add(ufc.getGroup());
+			}
+		} 
+		if (clause instanceof JoinPredicate) {
+			JoinPredicate jp = (JoinPredicate)clause;
+			if (jp.getJoinType() == JoinType.JOIN_CROSS || jp.getJoinType() == JoinType.JOIN_FULL_OUTER) {
+				return;
+			}
+			HashSet<GroupSymbol> leftPk = new HashSet<GroupSymbol>();
+			findKeyPreserved(jp.getLeftClause(), leftPk, metadata);
+			HashSet<GroupSymbol> rightPk = new HashSet<GroupSymbol>();
+			findKeyPreserved(jp.getRightClause(), rightPk, metadata);
+			
+			if (leftPk.isEmpty() && rightPk.isEmpty()) {
+				return;
+			}
+			
+			HashSet<GroupSymbol> leftGroups = new HashSet<GroupSymbol>();
+			HashSet<GroupSymbol> rightGroups = new HashSet<GroupSymbol>();
+			jp.getLeftClause().collectGroups(leftGroups);
+			jp.getRightClause().collectGroups(rightGroups);
+			
+			LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
+			LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
+			RuleChooseJoinStrategy.separateCriteria(leftGroups, rightGroups, leftExpressions, rightExpressions, jp.getJoinCriteria(), new LinkedList<Criteria>());
+		    
+			HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = createGroupMap(leftExpressions, rightExpressions);
+			if (!leftPk.isEmpty() && (jp.getJoinType() == JoinType.JOIN_INNER || jp.getJoinType() == JoinType.JOIN_LEFT_OUTER)) {
+				findKeyPreserved(keyPreservingGroups, leftPk, crits, true, metadata, rightPk);
+			} 
+			if (!rightPk.isEmpty() && (jp.getJoinType() == JoinType.JOIN_INNER || jp.getJoinType() == JoinType.JOIN_RIGHT_OUTER)) {
+				findKeyPreserved(keyPreservingGroups, rightPk, crits, false, metadata, leftPk);
+			}
+		}
+	}
+
+	private static HashMap<List<GroupSymbol>, List<HashSet<Object>>> createGroupMap(
+			LinkedList<Expression> leftExpressions,
+			LinkedList<Expression> rightExpressions) {
+		HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = new HashMap<List<GroupSymbol>, List<HashSet<Object>>>();
+		
+		for (int i = 0; i < leftExpressions.size(); i++) {
+			Expression lexpr = leftExpressions.get(i);
+			Expression rexpr = rightExpressions.get(i);
+			if (!(lexpr instanceof ElementSymbol) || !(rexpr instanceof ElementSymbol)) {
+				continue;
+			}
+			ElementSymbol les = (ElementSymbol)lexpr;
+			ElementSymbol res = (ElementSymbol)rexpr;
+			List<GroupSymbol> tbls = Arrays.asList(les.getGroupSymbol(), res.getGroupSymbol());
+			List<HashSet<Object>> ids = crits.get(tbls);
+			if (ids == null) {
+				ids = Arrays.asList(new HashSet<Object>(), new HashSet<Object>());
+				crits.put(tbls, ids);
+			}
+			ids.get(0).add(les.getMetadataID());
+			ids.get(1).add(res.getMetadataID());
+		}
+		return crits;
+	}
+
+	static private HashSet<GroupSymbol> findKeyPreserved(Set<GroupSymbol> keyPreservingGroups,
+		Set<GroupSymbol> pk,
+		HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits, boolean left, QueryMetadataInterface metadata, Set<GroupSymbol> otherGroups)
+		throws TeiidComponentException, QueryMetadataException {
+		HashSet<GroupSymbol> result = new HashSet<GroupSymbol>();
+		for (GroupSymbol gs : pk) {
+			for (Map.Entry<List<GroupSymbol>, List<HashSet<Object>>> entry : crits.entrySet()) {
+				if (!entry.getKey().get(left?0:1).equals(gs) || !otherGroups.contains(entry.getKey().get(left?1:0))) {
+					continue;
+				}
+				if (RuleRaiseAccess.matchesForeignKey(metadata, entry.getValue().get(left?0:1), entry.getValue().get(left?1:0), gs, false)) {
+					keyPreservingGroups.add(gs);
+					result.add(entry.getKey().get(left?1:0));
+				}
+			}
+		}
+		return result;
+	}
+    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/sql/lang/Query.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/Query.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/sql/lang/Query.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,459 +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.lang;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.core.util.HashCodeUtil;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
-
-/**
- * A representation of a data query.  A query consists of various parts,
- * referred to as clauses.  The following list the types of clauses
- * that a query can hold, and their purpose: <p>
- * <pre>
- *      CLAUSE          PURPOSE
- *      =========       ==============================================
- *      Select          Defines the variables data to be retrieved for
- *		From			Defines the groups to retrieve data from
- *      Criteria        Defines constraints on data retrieval ("where")
- * 		GroupBy			Defines how rows being returned should be grouped
- * 		Having			Defines how groups should be filtered, also a criteria
- *      OrderBy         Defines how the results should be sorted
- *	 	Option			Defines any extra options on the query
- * </pre>
- */
-public class Query extends QueryCommand {
-
-    /** The select clause. */
-    private Select select;
-
-	/** The from clause. */
-	private From from;
-	
-    /** The criteria specifying constraints on what data will be retrieved. */
-    private Criteria criteria;
-
-	/** The group by specifying how to group rows. */
-	private GroupBy groupBy;
-	
-	/** The having specifying which group rows will be returned. */
-	private Criteria having;
-
-	/** XML flag */
-	private boolean isXML;
-    
-    /** The into clause. */
-    private Into into;
-    
-    /** xml projected symbols */
-    private List<SingleElementSymbol> selectList;
-	
-    // =========================================================================
-    //                         C O N S T R U C T O R S
-    // =========================================================================
-    
-    /**
-     * Constructs a default instance of this class.
-     */
-    public Query() {
-        super();
-    }
-
-    /**
-     * Constructs an instance of this class given the specified clauses
-     * @param select SELECT clause
-     * @param from FROM clause
-     * @param criteria WHERE clause
-     * @param orderBy ORDER BY clause
-     * @param option OPTION clause
-     */
-    public Query( Select select, From from, Criteria criteria, OrderBy orderBy, Option option ) {
-        super();
-        setSelect( select );
-        setFrom( from );
-        setCriteria( criteria );
-        setOrderBy( orderBy );
-        setOption( option );
-    }
-
-    /**
-     * Constructs an instance of this class given all the clauses
-     * @param select SELECT clause
-     * @param from FROM clause
-     * @param criteria WHERE clause
-     * @param groupBy GROUP BY clause
-     * @param having HAVING clause
-     * @param orderBy ORDER BY clause
-     * @param option OPTION clause
-     */
-    public Query( Select select, From from, Criteria criteria, GroupBy groupBy, Criteria having, OrderBy orderBy, Option option ) {
-        super();
-        setSelect( select );
-        setFrom( from );
-        setCriteria( criteria );
-		setGroupBy( groupBy );
-		setHaving( having );
-        setOrderBy( orderBy );
-        setOption( option );
-    }
-
-   	/**
-	 * Return type of command.
-	 * @return TYPE_QUERY
-	 */
-	public int getType() {
-		return Command.TYPE_QUERY;
-	}
-    
-    // =========================================================================
-    //                     S E L E C T      M E T H O D S
-    // =========================================================================
-    
-    /**
-     * Get the select clause for the query.
-     * @return SELECT clause
-     */
-    public Select getSelect() {
-        return select;
-    }
-    
-    /**
-     * Set the select clause for the query.
-     * @param select SELECT clause
-     */
-    public void setSelect( Select select ) {
-        this.select = select;
-    }
-     
- 
-	/**
-	 * Get the xml flag for the query
-	 * @return boolean
-	 */
-	public boolean getIsXML() {
-		return isXML;
-	}
-    
-	/**
-	 * Get the xml flag for the query
-	 * @return boolean
-	 */
-	public void setIsXML(boolean isXML) {
-		this.isXML = isXML;
-	}
-      
-    // =========================================================================
-    //                     F R O M      M E T H O D S
-    // =========================================================================
-    
-    /**
-     * Get the from clause for the query.
-     * @return FROM clause
-     */
-    public From getFrom() {
-        return from;
-    }
-    
-    /**
-     * Set the from clause for the query.
-     * @param from FROM clause
-     */
-    public void setFrom( From from  ) {
-        this.from = from;
-    }
-        
-    // =========================================================================
-    //                   C R I T E R I A      M E T H O D S
-    // =========================================================================
-    
-    /**
-     * Get the criteria clause for the query.
-     * @return WHERE clause
-     */
-    public Criteria getCriteria() {
-        return criteria;
-    }
-    
-    /**
-     * Set the criteria clause for the query.
-     * @param criteria WHERE clause
-     */
-    public void setCriteria( Criteria criteria ) {
-        this.criteria = criteria;
-    }
-
-    /**
-     * Set the criteria clause to null
-     */
-    public void clearCriteria() {
-        this.criteria = null;
-    }
-
-    // =========================================================================
-    //                    G R O U P   B Y     M E T H O D S
-    // =========================================================================
-    
-    /**
-     * Get the group by clause for the query.
-     * @return GROUP BY clause
-     */
-    public GroupBy getGroupBy() {
-        return groupBy;
-    }
-    
-    /**
-     * Set the group by clause for the query.
-     * @param groupBy GROUP BY clause
-     */
-    public void setGroupBy( GroupBy groupBy ) {
-        this.groupBy = groupBy;
-    }
-
-
-    // =========================================================================
-    //                   H A V I N G      M E T H O D S
-    // =========================================================================
-    
-    /**
-     * Get the having clause for the query.
-     * @return HAVING clause
-     */
-    public Criteria getHaving() {
-        return having;
-    }
-    
-    /**
-     * Set the criteria clause for the query.
-     * @param having HAVING clause
-     */
-    public void setHaving( Criteria having ) {
-        this.having = having;
-    }
-
-    // =========================================================================
-    //                   I N T O      M E T H O D S
-    // =========================================================================
-
-    /**
-     * @return
-     */
-    public Into getInto() {
-        return into;
-    }
-
-    /**
-     * @param into
-     */
-    public void setInto(Into into) {
-        this.into = into;
-    }
-    
-    // =========================================================================
-    //                  P R O C E S S I N G     M E T H O D S
-    // =========================================================================
-        
-    public void acceptVisitor(LanguageVisitor visitor) {
-        visitor.visit(this);
-    }
-
-   	/**
-	 * Get the ordered list of all elements returned by this query.  These elements
-	 * may be ElementSymbols or ExpressionSymbols but in all cases each represents a 
-	 * single column.
-	 * @return Ordered list of SingleElementSymbol
-	 */
-	public List<SingleElementSymbol> getProjectedSymbols() {
-		if (!getIsXML()) {
-			if(getSelect() != null) { 
-                if(getInto() != null){
-                    //SELECT INTO clause
-                    return Command.getUpdateCommandSymbol();
-                }
-				return getSelect().getProjectedSymbols();
-			}
-			return Collections.emptyList();
-		}
-		if(selectList == null){
-			selectList = new ArrayList<SingleElementSymbol>(1);
-			ElementSymbol xmlElement = new ElementSymbol("xml"); //$NON-NLS-1$
-	        xmlElement.setType(DataTypeManager.DefaultDataClasses.XML);
-			selectList.add(xmlElement);
-		}
-		return selectList;
-	}
-	
-    // =========================================================================
-    //          O V E R R I D D E N     O B J E C T     M E T H O D S
-    // =========================================================================
-
-	/**
-	 * Deep clone Query to produce a new identical query.
-	 * @return Deep clone
-	 */
-	public Object clone() {		
-		Query copy = new Query();
-
-		if(select != null) {
-			copy.setSelect( (Select) select.clone());
-		}
-
-		if(from != null) {
-			copy.setFrom( (From) from.clone());
-		}
-
-		if(criteria != null) {
-			copy.setCriteria( (Criteria) criteria.clone());
-		}
-
-		if(groupBy != null) { 
-			copy.setGroupBy( (GroupBy) groupBy.clone());
-		} 
-		
-		if(having != null) { 
-			copy.setHaving( (Criteria) having.clone());
-		}	
-
-        if(getOrderBy() != null) {
-            copy.setOrderBy(getOrderBy().clone());
-        }
-
-        if(getLimit() != null) {
-            copy.setLimit( (Limit) getLimit().clone());
-        }
-        
-        copy.setWith(LanguageObject.Util.deepClone(this.getWith(), WithQueryCommand.class));
-
-        // Defect 13751: should clone isXML state.
-        copy.setIsXML(getIsXML());
-        
-        if(selectList != null){
-        	copy.selectList = LanguageObject.Util.deepClone(selectList, SingleElementSymbol.class);
-        }
-        
-        if (into != null) {
-        	copy.into = (Into)into.clone();
-        }
-        
-        copyMetadataState(copy);
-        
-		return copy;
-	}
-	
-    /**
-     * Compare two queries for equality.  Queries will only evaluate to equal if
-     * they are IDENTICAL: select variables are in the same order, criteria are in
-     * the same exact structure.  
-     * @param obj Other object
-     * @return True if equal
-     */
-    public boolean equals(Object obj) {
-    	if(this == obj) {
-    		return true;
-		}
-
-    	if(!(obj instanceof Query)) {
-    		return false;
-		}
-
-		Query other = (Query) obj;
-		
-        return EquivalenceUtil.areEqual(getSelect(), other.getSelect()) &&
-               EquivalenceUtil.areEqual(getFrom(), other.getFrom()) &&
-               EquivalenceUtil.areEqual(getCriteria(), other.getCriteria()) &&
-               EquivalenceUtil.areEqual(getGroupBy(), other.getGroupBy()) &&
-               EquivalenceUtil.areEqual(getHaving(), other.getHaving()) &&
-               EquivalenceUtil.areEqual(getOrderBy(), other.getOrderBy()) &&
-               EquivalenceUtil.areEqual(getLimit(), other.getLimit()) &&
-               EquivalenceUtil.areEqual(getWith(), other.getWith()) &&
-               getIsXML() == other.getIsXML() &&
-               sameOptionAndHint(other);
-    }
-
-    /**
-     * Get hashcode for query.  WARNING: This hash code relies on the hash codes of the
-     * Select and Criteria clauses.  If the query changes, it's hash code will change and
-     * it can be lost from collections.  Hash code is only valid after query has been
-     * completely constructed.
-     * @return Hash code
-     */
-    public int hashCode() {
-    	// For speed, this hash code relies only on the hash codes of its select
-    	// and criteria clauses, not on the from, order by, or option clauses
-    	int myHash = 0;
-    	myHash = HashCodeUtil.hashCode(myHash, this.select);
-		myHash = HashCodeUtil.hashCode(myHash, this.criteria);
-		return myHash;
-	}
-      
-	/**
-	 * @see org.teiid.query.sql.lang.Command#areResultsCachable()
-	 */
-	public boolean areResultsCachable() {
-		if(this.getInto() != null){
-			return false;
-		}
-		if (isXML) {
-			return true;
-		}
-		List projectedSymbols = getProjectedSymbols();
-		return areResultsCachable(projectedSymbols);
-	}
-
-	public static boolean areResultsCachable(Collection<? extends SingleElementSymbol> projectedSymbols) {
-		for (SingleElementSymbol projectedSymbol : projectedSymbols) {
-			if(projectedSymbol.getType() == DataTypeManager.DefaultDataClasses.OBJECT) {
-				return false;
-			}
-		}
-		return true;
-	}
-    
-    /** 
-     * @see org.teiid.query.sql.lang.QueryCommand#getProjectedQuery()
-     */
-    @Override
-    public Query getProjectedQuery() {
-        return this;
-    }
-    
-    @Override
-    public boolean returnsResultSet() {
-    	return into == null;
-    }
-    
-    public boolean hasAggregates() {
-    	return getGroupBy() != null 
-    	|| getHaving() != null 
-    	|| !AggregateSymbolCollectorVisitor.getAggregates(getSelect(), false).isEmpty();
-    }
-}  // END CLASS

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/sql/lang/Query.java (from rev 2801, trunk/engine/src/main/java/org/teiid/query/sql/lang/Query.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/sql/lang/Query.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/main/java/org/teiid/query/sql/lang/Query.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,459 @@
+/*
+ * 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.lang;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
+
+/**
+ * A representation of a data query.  A query consists of various parts,
+ * referred to as clauses.  The following list the types of clauses
+ * that a query can hold, and their purpose: <p>
+ * <pre>
+ *      CLAUSE          PURPOSE
+ *      =========       ==============================================
+ *      Select          Defines the variables data to be retrieved for
+ *		From			Defines the groups to retrieve data from
+ *      Criteria        Defines constraints on data retrieval ("where")
+ * 		GroupBy			Defines how rows being returned should be grouped
+ * 		Having			Defines how groups should be filtered, also a criteria
+ *      OrderBy         Defines how the results should be sorted
+ *	 	Option			Defines any extra options on the query
+ * </pre>
+ */
+public class Query extends QueryCommand {
+
+    /** The select clause. */
+    private Select select;
+
+	/** The from clause. */
+	private From from;
+	
+    /** The criteria specifying constraints on what data will be retrieved. */
+    private Criteria criteria;
+
+	/** The group by specifying how to group rows. */
+	private GroupBy groupBy;
+	
+	/** The having specifying which group rows will be returned. */
+	private Criteria having;
+
+	/** XML flag */
+	private boolean isXML;
+    
+    /** The into clause. */
+    private Into into;
+    
+    /** xml projected symbols */
+    private List<SingleElementSymbol> selectList;
+	
+    // =========================================================================
+    //                         C O N S T R U C T O R S
+    // =========================================================================
+    
+    /**
+     * Constructs a default instance of this class.
+     */
+    public Query() {
+        super();
+    }
+
+    /**
+     * Constructs an instance of this class given the specified clauses
+     * @param select SELECT clause
+     * @param from FROM clause
+     * @param criteria WHERE clause
+     * @param orderBy ORDER BY clause
+     * @param option OPTION clause
+     */
+    public Query( Select select, From from, Criteria criteria, OrderBy orderBy, Option option ) {
+        super();
+        setSelect( select );
+        setFrom( from );
+        setCriteria( criteria );
+        setOrderBy( orderBy );
+        setOption( option );
+    }
+
+    /**
+     * Constructs an instance of this class given all the clauses
+     * @param select SELECT clause
+     * @param from FROM clause
+     * @param criteria WHERE clause
+     * @param groupBy GROUP BY clause
+     * @param having HAVING clause
+     * @param orderBy ORDER BY clause
+     * @param option OPTION clause
+     */
+    public Query( Select select, From from, Criteria criteria, GroupBy groupBy, Criteria having, OrderBy orderBy, Option option ) {
+        super();
+        setSelect( select );
+        setFrom( from );
+        setCriteria( criteria );
+		setGroupBy( groupBy );
+		setHaving( having );
+        setOrderBy( orderBy );
+        setOption( option );
+    }
+
+   	/**
+	 * Return type of command.
+	 * @return TYPE_QUERY
+	 */
+	public int getType() {
+		return Command.TYPE_QUERY;
+	}
+    
+    // =========================================================================
+    //                     S E L E C T      M E T H O D S
+    // =========================================================================
+    
+    /**
+     * Get the select clause for the query.
+     * @return SELECT clause
+     */
+    public Select getSelect() {
+        return select;
+    }
+    
+    /**
+     * Set the select clause for the query.
+     * @param select SELECT clause
+     */
+    public void setSelect( Select select ) {
+        this.select = select;
+    }
+     
+ 
+	/**
+	 * Get the xml flag for the query
+	 * @return boolean
+	 */
+	public boolean getIsXML() {
+		return isXML;
+	}
+    
+	/**
+	 * Get the xml flag for the query
+	 * @return boolean
+	 */
+	public void setIsXML(boolean isXML) {
+		this.isXML = isXML;
+	}
+      
+    // =========================================================================
+    //                     F R O M      M E T H O D S
+    // =========================================================================
+    
+    /**
+     * Get the from clause for the query.
+     * @return FROM clause
+     */
+    public From getFrom() {
+        return from;
+    }
+    
+    /**
+     * Set the from clause for the query.
+     * @param from FROM clause
+     */
+    public void setFrom( From from  ) {
+        this.from = from;
+    }
+        
+    // =========================================================================
+    //                   C R I T E R I A      M E T H O D S
+    // =========================================================================
+    
+    /**
+     * Get the criteria clause for the query.
+     * @return WHERE clause
+     */
+    public Criteria getCriteria() {
+        return criteria;
+    }
+    
+    /**
+     * Set the criteria clause for the query.
+     * @param criteria WHERE clause
+     */
+    public void setCriteria( Criteria criteria ) {
+        this.criteria = criteria;
+    }
+
+    /**
+     * Set the criteria clause to null
+     */
+    public void clearCriteria() {
+        this.criteria = null;
+    }
+
+    // =========================================================================
+    //                    G R O U P   B Y     M E T H O D S
+    // =========================================================================
+    
+    /**
+     * Get the group by clause for the query.
+     * @return GROUP BY clause
+     */
+    public GroupBy getGroupBy() {
+        return groupBy;
+    }
+    
+    /**
+     * Set the group by clause for the query.
+     * @param groupBy GROUP BY clause
+     */
+    public void setGroupBy( GroupBy groupBy ) {
+        this.groupBy = groupBy;
+    }
+
+
+    // =========================================================================
+    //                   H A V I N G      M E T H O D S
+    // =========================================================================
+    
+    /**
+     * Get the having clause for the query.
+     * @return HAVING clause
+     */
+    public Criteria getHaving() {
+        return having;
+    }
+    
+    /**
+     * Set the criteria clause for the query.
+     * @param having HAVING clause
+     */
+    public void setHaving( Criteria having ) {
+        this.having = having;
+    }
+
+    // =========================================================================
+    //                   I N T O      M E T H O D S
+    // =========================================================================
+
+    /**
+     * @return
+     */
+    public Into getInto() {
+        return into;
+    }
+
+    /**
+     * @param into
+     */
+    public void setInto(Into into) {
+        this.into = into;
+    }
+    
+    // =========================================================================
+    //                  P R O C E S S I N G     M E T H O D S
+    // =========================================================================
+        
+    public void acceptVisitor(LanguageVisitor visitor) {
+        visitor.visit(this);
+    }
+
+   	/**
+	 * Get the ordered list of all elements returned by this query.  These elements
+	 * may be ElementSymbols or ExpressionSymbols but in all cases each represents a 
+	 * single column.
+	 * @return Ordered list of SingleElementSymbol
+	 */
+	public List<SingleElementSymbol> getProjectedSymbols() {
+		if (!getIsXML()) {
+			if(getSelect() != null) { 
+                if(getInto() != null){
+                    //SELECT INTO clause
+                    return Command.getUpdateCommandSymbol();
+                }
+				return getSelect().getProjectedSymbols();
+			}
+			return Collections.emptyList();
+		}
+		if(selectList == null){
+			selectList = new ArrayList<SingleElementSymbol>(1);
+			ElementSymbol xmlElement = new ElementSymbol("xml"); //$NON-NLS-1$
+	        xmlElement.setType(DataTypeManager.DefaultDataClasses.XML);
+			selectList.add(xmlElement);
+		}
+		return selectList;
+	}
+	
+    // =========================================================================
+    //          O V E R R I D D E N     O B J E C T     M E T H O D S
+    // =========================================================================
+
+	/**
+	 * Deep clone Query to produce a new identical query.
+	 * @return Deep clone
+	 */
+	public Object clone() {		
+		Query copy = new Query();
+
+		if(select != null) {
+			copy.setSelect( (Select) select.clone());
+		}
+
+		if(from != null) {
+			copy.setFrom( (From) from.clone());
+		}
+
+		if(criteria != null) {
+			copy.setCriteria( (Criteria) criteria.clone());
+		}
+
+		if(groupBy != null) { 
+			copy.setGroupBy( (GroupBy) groupBy.clone());
+		} 
+		
+		if(having != null) { 
+			copy.setHaving( (Criteria) having.clone());
+		}	
+
+        if(getOrderBy() != null) {
+            copy.setOrderBy(getOrderBy().clone());
+        }
+
+        if(getLimit() != null) {
+            copy.setLimit( (Limit) getLimit().clone());
+        }
+        
+        copy.setWith(LanguageObject.Util.deepClone(this.getWith(), WithQueryCommand.class));
+
+        // Defect 13751: should clone isXML state.
+        copy.setIsXML(getIsXML());
+        
+        if(selectList != null){
+        	copy.selectList = LanguageObject.Util.deepClone(selectList, SingleElementSymbol.class);
+        }
+        
+        if (into != null) {
+        	copy.into = (Into)into.clone();
+        }
+        
+        copyMetadataState(copy);
+        
+		return copy;
+	}
+	
+    /**
+     * Compare two queries for equality.  Queries will only evaluate to equal if
+     * they are IDENTICAL: select variables are in the same order, criteria are in
+     * the same exact structure.  
+     * @param obj Other object
+     * @return True if equal
+     */
+    public boolean equals(Object obj) {
+    	if(this == obj) {
+    		return true;
+		}
+
+    	if(!(obj instanceof Query)) {
+    		return false;
+		}
+
+		Query other = (Query) obj;
+		
+        return EquivalenceUtil.areEqual(getSelect(), other.getSelect()) &&
+               EquivalenceUtil.areEqual(getFrom(), other.getFrom()) &&
+               EquivalenceUtil.areEqual(getCriteria(), other.getCriteria()) &&
+               EquivalenceUtil.areEqual(getGroupBy(), other.getGroupBy()) &&
+               EquivalenceUtil.areEqual(getHaving(), other.getHaving()) &&
+               EquivalenceUtil.areEqual(getOrderBy(), other.getOrderBy()) &&
+               EquivalenceUtil.areEqual(getLimit(), other.getLimit()) &&
+               EquivalenceUtil.areEqual(getWith(), other.getWith()) &&
+               getIsXML() == other.getIsXML() &&
+               sameOptionAndHint(other);
+    }
+
+    /**
+     * Get hashcode for query.  WARNING: This hash code relies on the hash codes of the
+     * Select and Criteria clauses.  If the query changes, it's hash code will change and
+     * it can be lost from collections.  Hash code is only valid after query has been
+     * completely constructed.
+     * @return Hash code
+     */
+    public int hashCode() {
+    	// For speed, this hash code relies only on the hash codes of its select
+    	// and criteria clauses, not on the from, order by, or option clauses
+    	int myHash = 0;
+    	myHash = HashCodeUtil.hashCode(myHash, this.select);
+		myHash = HashCodeUtil.hashCode(myHash, this.criteria);
+		return myHash;
+	}
+      
+	/**
+	 * @see org.teiid.query.sql.lang.Command#areResultsCachable()
+	 */
+	public boolean areResultsCachable() {
+		if(this.getInto() != null){
+			return false;
+		}
+		if (isXML) {
+			return true;
+		}
+		List projectedSymbols = getProjectedSymbols();
+		return areResultsCachable(projectedSymbols);
+	}
+
+	public static boolean areResultsCachable(Collection<? extends SingleElementSymbol> projectedSymbols) {
+		for (SingleElementSymbol projectedSymbol : projectedSymbols) {
+			if(projectedSymbol.getType() == DataTypeManager.DefaultDataClasses.OBJECT) {
+				return false;
+			}
+		}
+		return true;
+	}
+    
+    /** 
+     * @see org.teiid.query.sql.lang.QueryCommand#getProjectedQuery()
+     */
+    @Override
+    public Query getProjectedQuery() {
+        return this;
+    }
+    
+    @Override
+    public boolean returnsResultSet() {
+    	return into == null;
+    }
+    
+    public boolean hasAggregates() {
+    	return getGroupBy() != null 
+    	|| getHaving() != null 
+    	|| !AggregateSymbolCollectorVisitor.getAggregates(getSelect(), false).isEmpty();
+    }
+}  // END CLASS

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,213 +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 static org.junit.Assert.*;
-
-import java.sql.ResultSet;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.cache.DefaultCacheFactory;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.dqp.internal.datamgr.FakeTransactionService;
-import org.teiid.dqp.service.AutoGenDataService;
-import org.teiid.dqp.service.FakeBufferService;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-
-public class TestDQPCore {
-
-    private DQPCore core;
-
-    @Before public void setUp() throws Exception {
-        DQPWorkContext context = FakeMetadataFactory.buildWorkContext(FakeMetadataFactory.exampleBQTCached(), FakeMetadataFactory.exampleBQTVDB());
-        context.getVDB().getModel("BQT3").setVisible(false); //$NON-NLS-1$
-
-        ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
-        context.getVDB().addAttchment(ConnectorManagerRepository.class, repo);
-        Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(new AutoGenDataService());
-        
-        core = new DQPCore();
-        core.setBufferService(new FakeBufferService());
-        core.setCacheFactory(new DefaultCacheFactory());
-        core.setTransactionService(new FakeTransactionService());
-        
-        core.start(new DQPConfiguration());
-    }
-    
-    @After public void tearDown() throws Exception {
-    	DQPWorkContext.setWorkContext(new DQPWorkContext());
-    	core.stop();
-    }
-
-    public RequestMessage exampleRequestMessage(String sql) {
-        RequestMessage msg = new RequestMessage(sql);
-        msg.setCursorType(ResultSet.TYPE_SCROLL_INSENSITIVE);
-        msg.setFetchSize(10);
-        msg.setPartialResults(false);
-        msg.setExecutionId(100);
-        return msg;
-    }
-
-    @Test public void testRequest1() throws Exception {
-    	helpExecute("SELECT IntKey FROM BQT1.SmallA", "a"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testUser1() throws Exception {
-        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = 'logon'"; //$NON-NLS-1$
-        String userName = "logon"; //$NON-NLS-1$
-        helpExecute(sql, userName);
-    }
-
-    @Test public void testUser2() throws Exception {
-        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() LIKE 'logon'"; //$NON-NLS-1$
-        String userName = "logon"; //$NON-NLS-1$
-        helpExecute(sql, userName);
-    }
-
-    @Test public void testUser3() throws Exception {
-        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() IN ('logon3') AND StringKey LIKE '1'"; //$NON-NLS-1$
-        String userName = "logon3"; //$NON-NLS-1$
-        helpExecute(sql, userName);
-    }
-
-    @Test public void testUser4() throws Exception {
-        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE 'logon4' = user() AND StringKey = '1'"; //$NON-NLS-1$
-        String userName = "logon4"; //$NON-NLS-1$
-        helpExecute(sql, userName);
-    }
-
-    @Test public void testUser5() throws Exception {
-        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() IS NULL "; //$NON-NLS-1$
-        String userName = "logon"; //$NON-NLS-1$
-        helpExecute(sql, userName);
-    }
-
-    @Test public void testUser6() throws Exception {
-        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = 'logon33' "; //$NON-NLS-1$
-        String userName = "logon"; //$NON-NLS-1$
-        helpExecute(sql, userName);
-    }
-
-    @Test public void testUser7() throws Exception {
-        String sql = "UPDATE BQT1.SmallA SET IntKey = 2 WHERE user() = 'logon' AND StringKey = '1' "; //$NON-NLS-1$
-        String userName = "logon"; //$NON-NLS-1$
-        helpExecute(sql, userName);
-    }
-
-    @Test public void testUser8() throws Exception {
-        String sql = "SELECT user(), StringKey FROM BQT1.SmallA WHERE IntKey = 1 "; //$NON-NLS-1$
-        String userName = "logon"; //$NON-NLS-1$
-        helpExecute(sql, userName);
-    }
-
-    @Test public void testUser9() throws Exception {
-        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = StringKey AND StringKey = '1' "; //$NON-NLS-1$
-        String userName = "1"; //$NON-NLS-1$
-        helpExecute(sql, userName);
-    }
-
-    @Test public void testEnvSessionId() throws Exception {
-        String sql = "SELECT env('sessionid') as SessionID"; //$NON-NLS-1$
-        String userName = "1"; //$NON-NLS-1$
-        ResultsMessage rm = helpExecute(sql, userName);
-        assertEquals("1", rm.getResults()[0].get(0)); //$NON-NLS-1$
-    }
-    
-    @Test public void testEnvSessionIdMixedCase() throws Exception {
-        String sql = "SELECT env('sEsSIonId') as SessionID"; //$NON-NLS-1$
-        String userName = "1"; //$NON-NLS-1$
-        ResultsMessage rm = helpExecute(sql, userName);
-        assertEquals("1", rm.getResults()[0].get(0)); //$NON-NLS-1$
-    }
-    
-    @Test public void testTxnAutoWrap() throws Exception {
-    	String sql = "SELECT * FROM BQT1.SmallA"; //$NON-NLS-1$
-    	helpExecute(sql, "a", 1, true); //$NON-NLS-1$
-    }
-    
-    /**
-     * Tests whether an exception result is sent when an exception occurs
-     * @since 4.3
-     */
-    @Test public void testPlanningException() throws Exception {
-        String sql = "SELECT IntKey FROM BQT1.BadIdea "; //$NON-NLS-1$
-        
-        RequestMessage reqMsg = exampleRequestMessage(sql);
-
-        Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
-        try {
-        	message.get(5000, TimeUnit.MILLISECONDS);
-        } catch (ExecutionException e) {
-        	assertTrue(e.getCause() instanceof QueryResolverException);
-        }
-    }
-    
-    @Ignore("visibility no longer ristricts access")
-	@Test public void testLookupVisibility() throws Exception {
-		helpTestVisibilityFails("select lookup('bqt3.smalla', 'intkey', 'stringkey', '?')"); //$NON-NLS-1$
-	}
-	
-	@Test public void testCancel() throws Exception {
-		assertFalse(this.core.cancelRequest(1L));
-	}
-    
-	public void helpTestVisibilityFails(String sql) throws Exception {
-        RequestMessage reqMsg = exampleRequestMessage(sql); 
-        reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_OFF);
-        Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
-        ResultsMessage results = message.get(5000, TimeUnit.MILLISECONDS);
-        assertEquals("[QueryValidatorException]Group does not exist: BQT3.SmallA", results.getException().toString()); //$NON-NLS-1$
-	}
-
-    ///////////////////////////Helper method///////////////////////////////////
-    private ResultsMessage helpExecute(String sql, String userName) throws Exception {
-    	return helpExecute(sql, userName, 1, false);
-    }
-
-    private ResultsMessage helpExecute(String sql, String userName, int sessionid, boolean txnAutoWrap) throws Exception {
-        RequestMessage reqMsg = exampleRequestMessage(sql);
-        DQPWorkContext.getWorkContext().getSession().setSessionId(String.valueOf(sessionid));
-        DQPWorkContext.getWorkContext().getSession().setUserName(userName);
-        if (txnAutoWrap) {
-        	reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_ON);
-        }
-
-        Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
-        ResultsMessage results = message.get(5000, TimeUnit.MILLISECONDS);
-        if (results.getException() != null) {
-        	throw results.getException();
-        }
-        return results;
-    }
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java (from rev 2802, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,216 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.sql.ResultSet;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.cache.DefaultCacheFactory;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.dqp.internal.datamgr.FakeTransactionService;
+import org.teiid.dqp.service.AutoGenDataService;
+import org.teiid.dqp.service.FakeBufferService;
+import org.teiid.query.unittest.FakeMetadataFactory;
+
+
+public class TestDQPCore {
+
+    private DQPCore core;
+
+    @Before public void setUp() throws Exception {
+        DQPWorkContext context = FakeMetadataFactory.buildWorkContext(FakeMetadataFactory.exampleBQTCached(), FakeMetadataFactory.exampleBQTVDB());
+        context.getVDB().getModel("BQT3").setVisible(false); //$NON-NLS-1$
+
+        ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
+        context.getVDB().addAttchment(ConnectorManagerRepository.class, repo);
+        Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(new AutoGenDataService());
+        
+        core = new DQPCore();
+        core.setBufferService(new FakeBufferService());
+        core.setCacheFactory(new DefaultCacheFactory());
+        core.setTransactionService(new FakeTransactionService());
+        
+        core.start(new DQPConfiguration());
+    }
+    
+    @After public void tearDown() throws Exception {
+    	DQPWorkContext.setWorkContext(new DQPWorkContext());
+    	core.stop();
+    }
+
+    public RequestMessage exampleRequestMessage(String sql) {
+        RequestMessage msg = new RequestMessage(sql);
+        msg.setCursorType(ResultSet.TYPE_SCROLL_INSENSITIVE);
+        msg.setFetchSize(10);
+        msg.setPartialResults(false);
+        msg.setExecutionId(100);
+        return msg;
+    }
+
+    @Test public void testRequest1() throws Exception {
+    	helpExecute("SELECT IntKey FROM BQT1.SmallA", "a"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testUser1() throws Exception {
+        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = 'logon'"; //$NON-NLS-1$
+        String userName = "logon"; //$NON-NLS-1$
+        helpExecute(sql, userName);
+    }
+
+    @Test public void testUser2() throws Exception {
+        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() LIKE 'logon'"; //$NON-NLS-1$
+        String userName = "logon"; //$NON-NLS-1$
+        helpExecute(sql, userName);
+    }
+
+    @Test public void testUser3() throws Exception {
+        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() IN ('logon3') AND StringKey LIKE '1'"; //$NON-NLS-1$
+        String userName = "logon3"; //$NON-NLS-1$
+        helpExecute(sql, userName);
+    }
+
+    @Test public void testUser4() throws Exception {
+        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE 'logon4' = user() AND StringKey = '1'"; //$NON-NLS-1$
+        String userName = "logon4"; //$NON-NLS-1$
+        helpExecute(sql, userName);
+    }
+
+    @Test public void testUser5() throws Exception {
+        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() IS NULL "; //$NON-NLS-1$
+        String userName = "logon"; //$NON-NLS-1$
+        helpExecute(sql, userName);
+    }
+
+    @Test public void testUser6() throws Exception {
+        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = 'logon33' "; //$NON-NLS-1$
+        String userName = "logon"; //$NON-NLS-1$
+        helpExecute(sql, userName);
+    }
+
+    @Test public void testUser7() throws Exception {
+        String sql = "UPDATE BQT1.SmallA SET IntKey = 2 WHERE user() = 'logon' AND StringKey = '1' "; //$NON-NLS-1$
+        String userName = "logon"; //$NON-NLS-1$
+        helpExecute(sql, userName);
+    }
+
+    @Test public void testUser8() throws Exception {
+        String sql = "SELECT user(), StringKey FROM BQT1.SmallA WHERE IntKey = 1 "; //$NON-NLS-1$
+        String userName = "logon"; //$NON-NLS-1$
+        helpExecute(sql, userName);
+    }
+
+    @Test public void testUser9() throws Exception {
+        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = StringKey AND StringKey = '1' "; //$NON-NLS-1$
+        String userName = "1"; //$NON-NLS-1$
+        helpExecute(sql, userName);
+    }
+
+    @Test public void testEnvSessionId() throws Exception {
+        String sql = "SELECT env('sessionid') as SessionID"; //$NON-NLS-1$
+        String userName = "1"; //$NON-NLS-1$
+        ResultsMessage rm = helpExecute(sql, userName);
+        assertEquals("1", rm.getResults()[0].get(0)); //$NON-NLS-1$
+    }
+    
+    @Test public void testEnvSessionIdMixedCase() throws Exception {
+        String sql = "SELECT env('sEsSIonId') as SessionID"; //$NON-NLS-1$
+        String userName = "1"; //$NON-NLS-1$
+        ResultsMessage rm = helpExecute(sql, userName);
+        assertEquals("1", rm.getResults()[0].get(0)); //$NON-NLS-1$
+    }
+    
+    @Test public void testTxnAutoWrap() throws Exception {
+    	String sql = "SELECT * FROM BQT1.SmallA"; //$NON-NLS-1$
+    	helpExecute(sql, "a", 1, true); //$NON-NLS-1$
+    }
+    
+    /**
+     * Tests whether an exception result is sent when an exception occurs
+     * @since 4.3
+     */
+    @Test public void testPlanningException() throws Exception {
+        String sql = "SELECT IntKey FROM BQT1.BadIdea "; //$NON-NLS-1$
+        
+        RequestMessage reqMsg = exampleRequestMessage(sql);
+
+        Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+        try {
+        	message.get(5000, TimeUnit.MILLISECONDS);
+        } catch (ExecutionException e) {
+        	assertTrue(e.getCause() instanceof QueryResolverException);
+        }
+    }
+    
+    @Ignore("visibility no longer ristricts access")
+	@Test public void testLookupVisibility() throws Exception {
+		helpTestVisibilityFails("select lookup('bqt3.smalla', 'intkey', 'stringkey', '?')"); //$NON-NLS-1$
+	}
+	
+	@Test public void testCancel() throws Exception {
+		assertFalse(this.core.cancelRequest(1L));
+	}
+    
+	public void helpTestVisibilityFails(String sql) throws Exception {
+        RequestMessage reqMsg = exampleRequestMessage(sql); 
+        reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_OFF);
+        Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+        ResultsMessage results = message.get(5000, TimeUnit.MILLISECONDS);
+        assertEquals("[QueryValidatorException]Group does not exist: BQT3.SmallA", results.getException().toString()); //$NON-NLS-1$
+	}
+
+    ///////////////////////////Helper method///////////////////////////////////
+    private ResultsMessage helpExecute(String sql, String userName) throws Exception {
+    	return helpExecute(sql, userName, 1, false);
+    }
+
+    private ResultsMessage helpExecute(String sql, String userName, int sessionid, boolean txnAutoWrap) throws Exception {
+        RequestMessage reqMsg = exampleRequestMessage(sql);
+        DQPWorkContext.getWorkContext().getSession().setSessionId(String.valueOf(sessionid));
+        DQPWorkContext.getWorkContext().getSession().setUserName(userName);
+        if (txnAutoWrap) {
+        	reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_ON);
+        }
+
+        Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+        assertNotNull(core.getClientState(String.valueOf(sessionid), false));
+        ResultsMessage results = message.get(5000, TimeUnit.MILLISECONDS);
+        core.terminateSession(String.valueOf(sessionid));
+        assertNull(core.getClientState(String.valueOf(sessionid), false));
+        if (results.getException() != null) {
+        	throw results.getException();
+        }
+        return results;
+    }
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/query/resolver/TestResolver.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/resolver/TestResolver.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/query/resolver/TestResolver.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,3098 +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.resolver;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-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.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryParserException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.FunctionTree;
-import org.teiid.query.function.UDFSource;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.optimizer.FakeFunctionMetadataSource;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.util.BindVariableVisitor;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.ProcedureReservedWords;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.OrderBy;
-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.Select;
-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.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.navigator.DeepPreOrderNavigator;
-import org.teiid.query.sql.proc.CommandStatement;
-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.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.SelectSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
-import org.teiid.query.unittest.RealMetadataFactory;
-import org.teiid.query.unittest.TimestampUtil;
-
- at SuppressWarnings("nls")
-public class TestResolver {
-
-	private FakeMetadataFacade metadata;
-
-	@Before public void setUp() {
-		metadata = FakeMetadataFactory.example1Cached();
-	}
-
-	// ################################## TEST HELPERS ################################
-
-	static Command helpParse(String sql) { 
-        try { 
-            return QueryParser.getQueryParser().parseCommand(sql);
-        } catch(TeiidException e) { 
-            throw new RuntimeException(e);
-        }
-	}
-    	
-    /**
-     * Helps resolve command, then check that the actual resolved Elements variables are the same as
-     * the expected variable names.  The variableNames param will be empty unless the subquery
-     * is a correlated subquery.
-     * @param sql Command to parse and resolve
-     * @param variableNames expected element symbol variable names, in order
-     * @return parsed and resolved Query
-     */
-    private Command helpResolveSubquery(String sql, String[] variableNames){
-        Query query = (Query)helpResolve(sql);
-        Collection<ElementSymbol> variables = getVariables(query);
-
-        assertTrue("Expected variables size " + variableNames.length + " but was " + variables.size(),  //$NON-NLS-1$ //$NON-NLS-2$
-                   variables.size() == variableNames.length);
-        Iterator variablesIter = variables.iterator();
-        for (int i=0; variablesIter.hasNext(); i++) {
-            ElementSymbol variable = (ElementSymbol)variablesIter.next();
-            assertTrue("Expected variable name " + variableNames[i] + " but was " + variable.getName(),  //$NON-NLS-1$ //$NON-NLS-2$
-                       variable.getName().equalsIgnoreCase(variableNames[i]));
-        }
-
-        if (variableNames.length == 0){
-            //There should be no TempMetadataIDs
-            Collection symbols = CheckNoTempMetadataIDsVisitor.checkSymbols(query);
-            assertTrue("Expected no symbols with temp metadataIDs, but got " + symbols, symbols.isEmpty()); //$NON-NLS-1$
-        }
-        
-        return query;         
-    }
-
-	public static Collection<ElementSymbol> getVariables(LanguageObject languageObject) {
-		Collection<ElementSymbol> variables = ElementCollectorVisitor.getElements(languageObject, false, true);
-    	for (Iterator<ElementSymbol> iterator = variables.iterator(); iterator.hasNext();) {
-			ElementSymbol elementSymbol = iterator.next();
-			if (!elementSymbol.isExternalReference()) {
-				iterator.remove();
-			}
-		}
-		return variables;
-	}
-    
-    public static Command helpResolve(String sql, QueryMetadataInterface queryMetadata, AnalysisRecord analysis){
-        return helpResolve(helpParse(sql), queryMetadata, analysis);
-    }
-    
-	private Command helpResolve(String sql) { 
-		return helpResolve(helpParse(sql));
-	}
-	
-    private Command helpResolve(Command command) {    
-        return helpResolve(command, this.metadata, AnalysisRecord.createNonRecordingRecord());  
-    }	
-
-	static Command helpResolve(Command command, QueryMetadataInterface queryMetadataInterface, AnalysisRecord analysis) {		
-        // resolve
-        try { 
-            QueryResolver.resolveCommand(command, queryMetadataInterface, analysis);
-        } catch(TeiidException e) {
-            throw new RuntimeException(e);
-        } 
-
-        CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
-        DeepPreOrderNavigator.doVisit(command, vis);
-        Collection unresolvedSymbols = vis.getUnresolvedSymbols();
-        assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
-        return command; 
-	}		
-
-	/**
-	 * Expect a QueryResolverException (not any other kind of Throwable)
-	 */
-	private void helpResolveFails(Command command) {
-		// resolve
-		QueryResolverException exception = null;
-		try {
-			QueryResolver.resolveCommand(command, metadata);
-		} catch(QueryResolverException e) {
-			exception = e;
-		} catch(TeiidException e) {
-			fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-		assertNotNull("Expected a QueryResolverException but got none.", exception); //$NON-NLS-1$
-	}
-
-    private Criteria helpResolveCriteria(String sql) { 
-        Criteria criteria = null;
-        
-        // parse
-        try { 
-            criteria = QueryParser.getQueryParser().parseCriteria(sql);
-           
-        } catch(TeiidException e) { 
-            fail("Exception during parsing (" + e.getClass().getName() + "): " + e.getMessage());    //$NON-NLS-1$ //$NON-NLS-2$
-        }   
-   
-   		// resolve
-        try { 
-            QueryResolver.resolveCriteria(criteria, metadata);
-        } catch(TeiidException e) {
-            e.printStackTrace();
-            fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        } 
-
-        CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
-        DeepPreOrderNavigator.doVisit(criteria, vis);
-        Collection unresolvedSymbols = vis.getUnresolvedSymbols();
-        assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
-        return criteria;
-    }
-    
-    private Command helpResolve(String sql, List bindings) { 
-       
-        // parse
-        Command command = helpParse(sql);
-        
-        // apply bindings
-        if(bindings != null) {
-            try { 
-                BindVariableVisitor.bindReferences(command, bindings, metadata);
-            } catch(TeiidException e) { 
-                fail("Exception during binding (" + e.getClass().getName() + "): " + e.getMessage());    //$NON-NLS-1$ //$NON-NLS-2$
-            }   
-        }
-        
-        // resolve
-        try { 
-            QueryResolver.resolveCommand(command, metadata);
-        } catch(TeiidException e) { 
-            fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        } 
-
-        CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
-        DeepPreOrderNavigator.doVisit(command, vis);
-
-        Collection unresolvedSymbols = vis.getUnresolvedSymbols();
-        assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
-        return command;
-    }
-
-    static void helpResolveException(String sql, QueryMetadataInterface queryMetadata){
-    	helpResolveException(sql, queryMetadata, null);	
-    }
-    
-    static void helpResolveException(String sql, QueryMetadataInterface queryMetadata, String expectedExceptionMessage){
-
-    	// parse
-        Command command = helpParse(sql);
-        
-        // resolve
-        try { 
-            QueryResolver.resolveCommand(command, queryMetadata);
-            fail("Expected exception for resolving " + sql);         //$NON-NLS-1$
-        } catch(QueryResolverException e) {
-        	if(expectedExceptionMessage != null){
-            	assertEquals(expectedExceptionMessage, e.getMessage());
-            }
-        } catch(TeiidComponentException e) {
-            throw new RuntimeException(e);
-        }       
-    }
-    
-	private void helpResolveException(String sql, String expectedExceptionMessage) {
-		TestResolver.helpResolveException(sql, this.metadata, expectedExceptionMessage);
-	}
-	
-	private void helpResolveException(String sql) {
-        TestResolver.helpResolveException(sql, this.metadata);
-	}
-	
-	private void helpCheckFrom(Query query, String[] groupIDs) { 
-		From from = query.getFrom();
-		List groups = from.getGroups();			
-		assertEquals("Wrong number of group IDs: ", groupIDs.length, groups.size()); //$NON-NLS-1$
-		
-		for(int i=0; i<groups.size(); i++) { 
-			GroupSymbol group = (GroupSymbol) groups.get(i);
-            String matchString = null;
-            if(group.getMetadataID() instanceof FakeMetadataObject) {
-                matchString = ((FakeMetadataObject)group.getMetadataID()).getName();
-            } else if(group.getMetadataID() instanceof TempMetadataID) {
-                matchString = ((TempMetadataID)group.getMetadataID()).getID();
-            }
-			assertEquals("Group ID does not match: ", groupIDs[i].toUpperCase(), matchString.toUpperCase()); //$NON-NLS-1$
-		}
-	}
-	
-	private void helpCheckSelect(Query query, String[] elementNames) {
-		Select select = query.getSelect();
-		List elements = select.getSymbols();
-		assertEquals("Wrong number of select symbols: ", elementNames.length, elements.size()); //$NON-NLS-1$
-
-		for(int i=0; i<elements.size(); i++) {
-			SelectSymbol symbol = (SelectSymbol) elements.get(i);
-			assertEquals("Element name does not match: ", elementNames[i].toUpperCase(), symbol.getName().toUpperCase()); //$NON-NLS-1$
-		}
-	}
-
-	private void helpCheckElements(LanguageObject langObj, String[] elementNames, String[] elementIDs) {
-		List elements = new ArrayList();
-		ElementCollectorVisitor.getElements(langObj, elements);
-		assertEquals("Wrong number of elements: ", elementNames.length, elements.size()); //$NON-NLS-1$
-
-		for(int i=0; i<elements.size(); i++) { 
-			ElementSymbol symbol = (ElementSymbol) elements.get(i);
-			assertEquals("Element name does not match: ", elementNames[i].toUpperCase(), symbol.getName().toUpperCase()); //$NON-NLS-1$
-			
-			FakeMetadataObject elementID = (FakeMetadataObject) symbol.getMetadataID();
-			assertNotNull("ElementSymbol " + symbol + " was not resolved and has no metadataID", elementID); //$NON-NLS-1$ //$NON-NLS-2$
-			assertEquals("ElementID name does not match: ", elementIDs[i].toUpperCase(), elementID.getName().toUpperCase()); //$NON-NLS-1$
-		}
-	}
-    
-    private void helpTestIsXMLQuery(String sql, boolean isXML) throws QueryResolverException, QueryMetadataException, TeiidComponentException {
-        // parse
-        Query query = (Query) helpParse(sql);
-
-        // check whether it's xml
-        boolean actual = QueryResolver.isXMLQuery(query, metadata);
-        assertEquals("Wrong answer for isXMLQuery", isXML, actual); //$NON-NLS-1$
-    }
-	
-    /**
-     * Helper method to resolve an exec aka stored procedure, then check that the
-     * expected parameter expressions are the same as actual parameter expressions. 
-     * @param sql
-     * @param expectedParameterExpressions
-     * @since 4.3
-     */
-    private StoredProcedure helpResolveExec(String sql, Object[] expectedParameterExpressions) {
-
-        StoredProcedure proc = (StoredProcedure)helpResolve(sql);
-        
-        List params = proc.getParameters();
-
-        // Remove all but IN and IN/OUT params
-        Iterator paramIter = params.iterator();
-        while (paramIter.hasNext()) {
-            final SPParameter param = (SPParameter)paramIter.next();
-            if (param.getParameterType() != ParameterInfo.IN && param.getParameterType() != ParameterInfo.INOUT) {
-                paramIter.remove();
-            }
-        }
-
-        // Check remaining params against expected expressions
-        assertEquals(expectedParameterExpressions.length, params.size());
-        for (int i=0; i<expectedParameterExpressions.length; i++) {
-            SPParameter param = (SPParameter)params.get(i);
-            if (expectedParameterExpressions[i] == null) {
-                assertNull(param.getExpression());
-            } else {
-                assertEquals(expectedParameterExpressions[i], param.getExpression());
-            }
-        }
-        
-        return proc;
-    }
-        
-    
-	// ################################## ACTUAL TESTS ################################
-	
-	
-	@Test public void testElementSymbolForms() {
-        String sql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 AS a, e4 AS b FROM pm1.g1"; //$NON-NLS-1$
-		Query resolvedQuery = (Query) helpResolve(sql);
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e2", "a", "b" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-		helpCheckElements(resolvedQuery.getSelect(), 
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
-	}
-
-	@Test public void testElementSymbolFormsWithAliasedGroup() {
-        String sql = "SELECT x.e1, e2, x.e3 AS a, e4 AS b FROM pm1.g1 AS x"; //$NON-NLS-1$
-		Query resolvedQuery = (Query) helpResolve(sql);
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "x.e1", "x.e2", "a", "b" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-		helpCheckElements(resolvedQuery.getSelect(),
-			new String[] { "x.e1", "x.e2", "x.e3", "x.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
-	}
-
-    @Test public void testGroupWithVDB() {
-        String sql = "SELECT e1 FROM myvdb.pm1.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
-    }
-
-    @Test public void testAliasedGroupWithVDB() {
-        String sql = "SELECT e1 FROM myvdb.pm1.g1 AS x"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString());         //$NON-NLS-1$
-    }
-    
-    @Test public void testPartiallyQualifiedGroup1() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT e1 FROM cat2.cat3.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1" }); //$NON-NLS-1$
-    }    
-    
-    @Test public void testPartiallyQualifiedGroup2() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT e1 FROM cat1.g2"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.g2" }); //$NON-NLS-1$
-    }
-    
-    @Test public void testPartiallyQualifiedGroup3() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT e1 FROM cat1.cat2.cat3.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1" }); //$NON-NLS-1$
-    }
-    
-    @Test public void testPartiallyQualifiedGroup4() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT e1 FROM cat2.g2"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm2.cat2.g2" }); //$NON-NLS-1$
-    }
-    
-    @Test public void testPartiallyQualifiedGroup5() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT e1 FROM cat2.g3"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat2.g3" }); //$NON-NLS-1$
-    }    
-    
-    @Test public void testPartiallyQualifiedGroup6() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT e1 FROM cat1.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm2.cat1.g1" }); //$NON-NLS-1$
-    }    
-    
-    @Test public void testPartiallyQualifiedGroup7() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT e1 FROM g4"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm2.g4" }); //$NON-NLS-1$
-    }    
-    
-    @Test public void testPartiallyQualifiedGroup8() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT e1 FROM pm2.g3"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm2.g3" }); //$NON-NLS-1$
-    }
-    
-    @Test public void testPartiallyQualifiedGroupWithAlias() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT X.e1 FROM cat2.cat3.g1 as X"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1" }); //$NON-NLS-1$
-    } 
-    
-    @Test public void testPartiallyQualifiedElement1() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT cat2.cat3.g1.e1 FROM cat2.cat3.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1" }); //$NON-NLS-1$
-    }
-
-    /** defect 12536 */
-    @Test public void testPartiallyQualifiedElement2() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT cat3.g1.e1 FROM cat2.cat3.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1" }); //$NON-NLS-1$
-    }
-    
-    /** defect 12536 */
-    @Test public void testPartiallyQualifiedElement3() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT cat3.g1.e1 FROM cat2.cat3.g1, cat1.g2"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1" }); //$NON-NLS-1$
-    }
-    
-    /** defect 12536 */
-    @Test public void testPartiallyQualifiedElement4() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT cat3.g1.e1, cat1.g2.e1 FROM cat2.cat3.g1, cat1.g2"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.g2.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-    
-    @Test public void testPartiallyQualifiedElement5() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT cat3.g1.e1, cat1.g2.e1 FROM myvdb.pm1.cat1.cat2.cat3.g1, pm1.cat1.g2"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.g2.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-    
-    /** defect 12536 */
-    @Test public void testPartiallyQualifiedElement6() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT cat3.g1.e1, e2 FROM cat2.cat3.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-	    helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.cat2.cat3.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-    
-    @Test public void testPartiallyQualifiedElement7() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT cat3.g1.e1, cat2.cat3.g1.e2, g1.e3 FROM pm1.cat1.cat2.cat3.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.cat2.cat3.g1.e2", "pm1.cat1.cat2.cat3.g1.e3" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    } 
-    
-    @Test public void testFailPartiallyQualifiedGroup1() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT e1 FROM cat3.g1"); //$NON-NLS-1$
-    }
-    
-    @Test public void testFailPartiallyQualifiedGroup2() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT e1 FROM g1"); //$NON-NLS-1$
-    }
-    
-    @Test public void testFailPartiallyQualifiedGroup3() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT e1 FROM g2"); //$NON-NLS-1$
-    }
-    
-    @Test public void testFailPartiallyQualifiedGroup4() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT e1 FROM g3"); //$NON-NLS-1$
-    }
-    
-    @Test public void testFailPartiallyQualifiedGroup5() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT e1 FROM g5");		 //$NON-NLS-1$
-    }
-    
-    @Test public void testFailPartiallyQualifiedElement1() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT cat3.g1.e1 FROM pm1.cat1.cat2.cat3.g1, pm2.cat3.g1"); //$NON-NLS-1$
-    }
-    
-    @Test public void testFailPartiallyQualifiedElement2() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT g1.e1 FROM pm1.cat1.cat2.cat3.g1, pm2.cat3.g1"); //$NON-NLS-1$
-    }
-    
-    @Test public void testFailPartiallyQualifiedElement3() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2, pm1.cat2.g3"); //$NON-NLS-1$
-    }
-    
-    @Test public void testFailPartiallyQualifiedElement4() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2"); //$NON-NLS-1$
-    }
-    
-    @Test public void testFailPartiallyQualifiedElement5() {
-    	metadata = FakeMetadataFactory.example3();
-		helpResolveException("SELECT cat3.g1.e1 FROM g1"); //$NON-NLS-1$
-    }    
-
-    @Test public void testElementWithVDB() {
-        String sql = "SELECT myvdb.pm1.g1.e1 FROM pm1.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
-        helpCheckElements(resolvedQuery.getSelect(),
-            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
-            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
-        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
-    }
-
-    @Test public void testAliasedElementWithVDB() {
-        Query resolvedQuery = (Query) helpResolve("SELECT myvdb.pm1.g1.e1 AS x FROM pm1.g1"); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
-        helpCheckElements(resolvedQuery.getSelect(),
-            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
-            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
-    }
-
-	@Test public void testSelectStar() {
-		Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g1"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
-		helpCheckElements(resolvedQuery.getSelect(),
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}
-
-	@Test public void testSelectStarFromAliasedGroup() {
-		Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g1 as x"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
-		helpCheckElements(resolvedQuery.getSelect(),
-			new String[] { "x.e1", "x.e2", "x.e3", "x.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}
-
-	@Test public void testSelectStarFromMultipleAliasedGroups() {
-		Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g1 as x, pm1.g1 as y"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1", "pm1.g1" }); //$NON-NLS-1$ //$NON-NLS-2$
-		helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
-		helpCheckElements(resolvedQuery.getSelect(),
-			new String[] { "x.e1", "x.e2", "x.e3", "x.e4", "y.e1", "y.e2", "y.e3", "y.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4", "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
-	}
-
-    @Test public void testSelectStarWhereSomeElementsAreNotSelectable() {
-        Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g4"); //$NON-NLS-1$
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.g4" }); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
-        helpCheckElements(resolvedQuery.getSelect(),
-            new String[] { "pm1.g4.e1", "pm1.g4.e3" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { "pm1.g4.e1", "pm1.g4.e3" } ); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testSelectGroupStarWhereSomeElementsAreNotSelectable() {
-        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g4.* FROM pm1.g4"); //$NON-NLS-1$
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.g4" }); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.g4.*" }); //$NON-NLS-1$
-        helpCheckElements(resolvedQuery.getSelect(),
-            new String[] { "pm1.g4.e1", "pm1.g4.e3" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { "pm1.g4.e1", "pm1.g4.e3" } ); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-	@Test public void testFullyQualifiedSelectStar() {
-		Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.* FROM pm1.g1"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.*" }); //$NON-NLS-1$
-		helpCheckElements(resolvedQuery.getSelect(),
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}
-
-	@Test public void testSelectAllInAliasedGroup() {
-		Query resolvedQuery = (Query) helpResolve("SELECT x.* FROM pm1.g1 as x"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "x.*" }); //$NON-NLS-1$
-		helpCheckElements(resolvedQuery.getSelect(),
-			new String[] { "x.e1", "x.e2", "x.e3", "x.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}
-
-	@Test public void testSelectExpressions() {
-		Query resolvedQuery = (Query) helpResolve("SELECT e1, concat(e1, 's'), concat(e1, 's') as c FROM pm1.g1"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "expr", "c" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		helpCheckElements(resolvedQuery.getSelect(),
-			new String[] { "pm1.g1.e1", "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			new String[] { "pm1.g1.e1", "pm1.g1.e1", "pm1.g1.e1" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-
-	@Test public void testSelectCountStar() {
-		Query resolvedQuery = (Query) helpResolve("SELECT count(*) FROM pm1.g1"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "count" }); //$NON-NLS-1$
-		helpCheckElements(resolvedQuery.getSelect(), new String[] { }, new String[] { } );
-	}
-	
-	@Test public void testMultipleIdenticalElements() { 
-		Query resolvedQuery = (Query) helpResolve("SELECT e1, e1 FROM pm1.g1"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
-		helpCheckElements(resolvedQuery.getSelect(), 
-			new String[] { "pm1.g1.e1", "pm1.g1.e1" },  //$NON-NLS-1$ //$NON-NLS-2$
-			new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	@Test public void testMultipleIdenticalElements2() { 
-		Query resolvedQuery = (Query) helpResolve("SELECT e1, pm1.g1.e1 FROM pm1.g1"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
-		helpCheckElements(resolvedQuery.getSelect(), 
-			new String[] { "pm1.g1.e1", "pm1.g1.e1" },  //$NON-NLS-1$ //$NON-NLS-2$
-			new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	@Test public void testMultipleIdenticalElements3() { 
-		Query resolvedQuery = (Query) helpResolve("SELECT e1, e1 as x FROM pm1.g1"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
-		helpCheckElements(resolvedQuery.getSelect(), 
-			new String[] { "pm1.g1.e1", "pm1.g1.e1" },  //$NON-NLS-1$ //$NON-NLS-2$
-			new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-	@Test public void testDifferentElementsSameName() { 
-		Query resolvedQuery = (Query) helpResolve("SELECT e1 as x, e2 as x FROM pm1.g2"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g2" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "x", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
-		helpCheckElements(resolvedQuery.getSelect(), 
-			new String[] { "pm1.g2.e1", "pm1.g2.e2" },  //$NON-NLS-1$ //$NON-NLS-2$
-			new String[] { "pm1.g2.e1", "pm1.g2.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	@Test public void testDifferentConstantsSameName() { 
-		Query resolvedQuery = (Query) helpResolve("SELECT 1 as x, 2 as x FROM pm1.g2"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g2" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "x", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
-		helpCheckElements(resolvedQuery.getSelect(), 
-			new String[] { }, 
-			new String[] { });
-	}
-	
-	@Test public void testFailSameGroupsWithSameNames() { 
-		helpResolveException("SELECT * FROM pm1.g1 as x, pm1.g1 as x"); //$NON-NLS-1$
-	}
-
-	@Test public void testFailDifferentGroupsWithSameNames() { 
-		helpResolveException("SELECT * FROM pm1.g1 as x, pm1.g2 as x"); //$NON-NLS-1$
-	}
-
-	@Test public void testFailAmbiguousElement() { 
-		helpResolveException("SELECT e1 FROM pm1.g1, pm1.g2"); //$NON-NLS-1$
-	}
-
-	@Test public void testFailAmbiguousElementAliasedGroup() { 
-		helpResolveException("SELECT e1 FROM pm1.g1 as x, pm1.g1"); //$NON-NLS-1$
-	}
-
-	@Test public void testFailFullyQualifiedElementUnknownGroup() { 
-		helpResolveException("SELECT pm1.g1.e1 FROM pm1.g2"); //$NON-NLS-1$
-	}
-
-	@Test public void testFailUnknownGroup() { 
-		helpResolveException("SELECT x.e1 FROM x"); //$NON-NLS-1$
-	}
-
-	@Test public void testFailUnknownElement() { 
-		helpResolveException("SELECT x FROM pm1.g1"); //$NON-NLS-1$
-	}
-
-    @Test public void testFailFunctionOfAggregatesInSelect() {        
-        helpResolveException("SELECT (SUM(e0) * COUNT(e0)) FROM test.group GROUP BY e0"); //$NON-NLS-1$
-    }
-	
-	/*
-	 * per defect 4404 
-	 */
-	@Test public void testFailGroupNotReferencedByAlias() { 
-		helpResolveException("SELECT pm1.g1.x FROM pm1.g1 as H"); //$NON-NLS-1$
-	}
-
-	/*
-	 * per defect 4404 - this one reproduced the defect,
-	 * then succeeded after the fix
-	 */
-	@Test public void testFailGroupNotReferencedByAliasSelectAll() { 
-		helpResolveException("SELECT pm1.g1.* FROM pm1.g1 as H"); //$NON-NLS-1$
-	}
-
-	@Test public void testComplicatedQuery() {
-		Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e2 as y, pm1.g1.E3 as z, CONVERT(pm1.g1.e1, integer) * 1000 as w  FROM pm1.g1 WHERE e1 <> 'x'"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "y", "z", "w" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		helpCheckElements(resolvedQuery, 
-			new String[] { "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e1" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}
-	
-	@Test public void testJoinQuery() {
-		Query resolvedQuery = (Query) helpResolve("SELECT pm3.g1.e2, pm3.g2.e2 FROM pm3.g1, pm3.g2 WHERE pm3.g1.e2=pm3.g2.e2"); //$NON-NLS-1$
-		helpCheckFrom(resolvedQuery, new String[] { "pm3.g1", "pm3.g2" }); //$NON-NLS-1$ //$NON-NLS-2$
-		helpCheckSelect(resolvedQuery, new String[] { "pm3.g1.e2", "pm3.g2.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
-		helpCheckElements(resolvedQuery, 
-			new String[] { "pm3.g1.e2", "pm3.g2.e2", "pm3.g1.e2", "pm3.g2.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { "pm3.g1.e2", "pm3.g2.e2", "pm3.g1.e2", "pm3.g2.e2" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}
-	
-    @Test public void testHavingRequiringConvertOnAggregate1() {
-        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MAX(e2) > 1.2"); //$NON-NLS-1$
-    }
-
-    @Test public void testHavingRequiringConvertOnAggregate2() {
-        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MIN(e2) > 1.2"); //$NON-NLS-1$
-    }
-
-    @Test public void testHavingRequiringConvertOnAggregate3() {
-        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING 1.2 > MAX(e2)"); //$NON-NLS-1$
-    }
-
-    @Test public void testHavingRequiringConvertOnAggregate4() {
-        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING 1.2 > MIN(e2)"); //$NON-NLS-1$
-    }
-
-    @Test public void testHavingWithAggsOfDifferentTypes() {
-        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MIN(e1) = MIN(e2)"); //$NON-NLS-1$
-    }
-    
-    @Test public void testCaseInGroupBy() {
-        String sql = "SELECT SUM(e2) FROM pm1.g1 GROUP BY CASE WHEN e2 = 0 THEN 1 ELSE 2 END"; //$NON-NLS-1$
-        Command command = helpResolve(sql);
-        assertEquals(sql, command.toString());
-        
-        helpCheckElements(command, new String[] {"pm1.g1.e2", "pm1.g1.e2"}, new String[] {"pm1.g1.e2", "pm1.g1.e2"});  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
-    }
-
-    @Test public void testFunctionInGroupBy() {
-        String sql = "SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)"; //$NON-NLS-1$
-        Command command = helpResolve(sql);
-        assertEquals(sql, command.toString());
-        
-        helpCheckElements(command, new String[] {"pm1.g1.e2", "pm1.g1.e2"}, new String[] {"pm1.g1.e2", "pm1.g1.e2"});  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
-    }
-
-	@Test public void testUnknownFunction() {	    
-		helpResolveException("SELECT abc(e1) FROM pm1.g1", "Error Code:ERR.015.008.0039 Message:The function 'abc(e1)' is an unknown form.  Check that the function name and number of arguments is correct."); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	@Test public void testConversionNotPossible() {	    
-		helpResolveException("SELECT dayofmonth('2002-01-01') FROM pm1.g1", "Error Code:ERR.015.008.0040 Message:The function 'dayofmonth('2002-01-01')' is a valid function form, but the arguments do not match a known type signature and cannot be converted using implicit type conversions."); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-    
-    @Test public void testResolveParameters() {
-        List bindings = new ArrayList();
-        bindings.add("pm1.g2.e1"); //$NON-NLS-1$
-        bindings.add("pm1.g2.e2"); //$NON-NLS-1$
-        
-        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, ? FROM pm1.g1 WHERE pm1.g1.e1 = ?", bindings); //$NON-NLS-1$
-
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "expr" }); //$NON-NLS-1$ //$NON-NLS-2$
-        helpCheckElements(resolvedQuery.getCriteria(), 
-            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
-            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
-            
-    }
-
-    @Test public void testResolveParametersInsert() {
-        List bindings = new ArrayList();
-        bindings.add("pm1.g2.e1"); //$NON-NLS-1$
-        
-        helpResolve("INSERT INTO pm1.g1 (e1) VALUES (?)", bindings); //$NON-NLS-1$
-    }
-    
-    @Test public void testResolveParametersExec() {
-        List bindings = new ArrayList();
-        bindings.add("pm1.g2.e1"); //$NON-NLS-1$
-        
-        Query resolvedQuery = (Query)helpResolve("SELECT * FROM (exec pm1.sq2(?)) as a", bindings); //$NON-NLS-1$
-        //verify the type of the reference is resolved
-        List refs = ReferenceCollectorVisitor.getReferences(resolvedQuery);
-        Reference ref = (Reference)refs.get(0);
-        assertNotNull(ref.getType());
-    }
-
-    @Test public void testUseNonExistentAlias() {
-        helpResolveException("SELECT portfoliob.e1 FROM ((pm1.g1 AS portfoliob JOIN pm1.g2 AS portidentb ON portfoliob.e1 = portidentb.e1) RIGHT OUTER JOIN pm1.g3 AS identifiersb ON portidentb.e1 = 'ISIN' and portidentb.e2 = identifiersb.e2) RIGHT OUTER JOIN pm1.g1 AS issuesb ON a.identifiersb.e1 = issuesb.e1"); //$NON-NLS-1$
-    }       
-
-    @Test public void testCriteria1() {                  
-        CompareCriteria expected = new CompareCriteria();
-        ElementSymbol es = new ElementSymbol("pm1.g1.e1"); //$NON-NLS-1$
-        GroupSymbol gs = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
-        es.setGroupSymbol(gs);
-        expected.setLeftExpression(es);
-        expected.setOperator(CompareCriteria.EQ);
-        expected.setRightExpression(new Constant("abc")); //$NON-NLS-1$
-
-        Criteria actual = helpResolveCriteria("pm1.g1.e1 = 'abc'"); //$NON-NLS-1$
-
-        assertEquals("Did not match expected criteria", expected, actual);         //$NON-NLS-1$
-    }
-        
-    @Test public void testSubquery1() {
-        Query resolvedQuery = (Query) helpResolve("SELECT e1 FROM pm1.g1, (SELECT pm1.g2.e1 AS x FROM pm1.g2) AS y WHERE e1 = x"); //$NON-NLS-1$
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1", "y" }); //$NON-NLS-1$ //$NON-NLS-2$
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
-        helpCheckElements(resolvedQuery.getSelect(),
-            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
-            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
-        
-    }
-    
-    @Test public void testStoredQuery1() {                
-        StoredProcedure proc = (StoredProcedure) helpResolve("EXEC pm1.sq2('abc')"); //$NON-NLS-1$
-        
-        // Check number of resolved parameters
-        List params = proc.getParameters();
-        assertEquals("Did not get expected parameter count", 2, params.size()); //$NON-NLS-1$
-        
-        // Check resolved parameters
-        SPParameter param1 = (SPParameter) params.get(0);
-        helpCheckParameter(param1, ParameterInfo.RESULT_SET, 1, "pm1.sq2.ret", java.sql.ResultSet.class, null); //$NON-NLS-1$
-
-        SPParameter param2 = (SPParameter) params.get(1);
-        helpCheckParameter(param2, ParameterInfo.IN, 2, "pm1.sq2.in", DataTypeManager.DefaultDataClasses.STRING, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-	/**
-	 * per defect 8211 - Input params do not have to be numbered sequentially in metadata.  For example,
-	 * the first input param can be #1 and the second input param can be #3.  (This occurs in 
-	 * QueryBuilder's metadata where the return param happens to be created in between the two
-	 * input params and is numbered #2, but is not loaded into QueryBuilder's runtime env).  
-	 * When the user's query is parsed and resolved, the placeholder
-	 * input params are numbered #1 and #2.  This test tests that this disparity in ordering should not
-	 * be a problem as long as RELATIVE ordering is in synch.
-	 */
-	@Test public void testStoredQueryParamOrdering_8211() {                
-		StoredProcedure proc = (StoredProcedure) helpResolve("EXEC pm1.sq3a('abc', 123)"); //$NON-NLS-1$
-		
-		// Check number of resolved parameters
-		List params = proc.getParameters();
-		assertEquals("Did not get expected parameter count", 2, params.size()); //$NON-NLS-1$
-        
-		// Check resolved parameters
-		SPParameter param1 = (SPParameter) params.get(0);
-		helpCheckParameter(param1, ParameterInfo.IN, 1, "pm1.sq3a.in", DataTypeManager.DefaultDataClasses.STRING, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
-
-		SPParameter param2 = (SPParameter) params.get(1);
-		helpCheckParameter(param2, ParameterInfo.IN, 3, "pm1.sq3a.in2", DataTypeManager.DefaultDataClasses.INTEGER, new Constant(new Integer(123))); //$NON-NLS-1$
-	}    
-    
-    private void helpCheckParameter(SPParameter param, int paramType, int index, String name, Class type, Expression expr) {
-        assertEquals("Did not get expected parameter type", paramType, param.getParameterType()); //$NON-NLS-1$
-        assertEquals("Did not get expected index for param", index, param.getIndex()); //$NON-NLS-1$
-        assertEquals("Did not get expected name for param", name, param.getName()); //$NON-NLS-1$
-        assertEquals("Did not get expected type for param", type, param.getClassType()); //$NON-NLS-1$
-        assertEquals("Did not get expected type for param", expr, param.getExpression());                 //$NON-NLS-1$
-    }
-    
-    @Test public void testStoredSubQuery1() {
-        Query resolvedQuery = (Query) helpResolve("select x.e1 from (EXEC pm1.sq1()) as x"); //$NON-NLS-1$
-        helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "x.e1" });         //$NON-NLS-1$
-    }
-    
-    @Test public void testStoredSubQuery2() {
-        Query resolvedQuery = (Query) helpResolve("select x.e1 from (EXEC pm1.sq3('abc', 5)) as x"); //$NON-NLS-1$
-        helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "x.e1" });         //$NON-NLS-1$
-    }
-
-    @Test public void testStoredSubQuery3() {
-        Query resolvedQuery = (Query) helpResolve("select * from (EXEC pm1.sq2('abc')) as x"); //$NON-NLS-1$
-        helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
-        
-        List elements = (List) ElementCollectorVisitor.getElements(resolvedQuery.getSelect(), false);
-        
-        ElementSymbol elem1 = (ElementSymbol)elements.get(0);
-        assertEquals("Did not get expected element", "X.e1", elem1.getName() ); //$NON-NLS-1$ //$NON-NLS-2$
-        assertEquals("Did not get expected type", DataTypeManager.DefaultDataClasses.STRING, elem1.getType()); //$NON-NLS-1$
-
-        ElementSymbol elem2 = (ElementSymbol)elements.get(1);
-        assertEquals("Did not get expected element", "X.e2", elem2.getName() ); //$NON-NLS-1$ //$NON-NLS-2$
-        assertEquals("Did not get expected type", DataTypeManager.DefaultDataClasses.INTEGER, elem2.getType()); //$NON-NLS-1$
-    }
-
-    @Test public void testStoredQueryTransformationWithVariable() throws Exception {
-        Command command = QueryParser.getQueryParser().parseCommand("SELECT * FROM pm1.g1 WHERE pm1.sq5.in1 = 5"); //$NON-NLS-1$
-        
-        // Construct command metadata 
-        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5");  //$NON-NLS-1$
-        ArrayList sqParams = new ArrayList();
-        ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
-        in.setType(DataTypeManager.DefaultDataClasses.STRING);
-        sqParams.add(in);
-        Map externalMetadata = new HashMap();
-        externalMetadata.put(sqGroup, sqParams);
-        
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-
-        // Verify results        
-        helpCheckFrom((Query)command, new String[] { "pm1.g1" });         //$NON-NLS-1$
-        Collection vars = getVariables(command);
-        assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
-    }
-
-    @Test public void testStoredQueryTransformationWithVariable2() throws Exception {
-        Command command = QueryParser.getQueryParser().parseCommand("SELECT * FROM pm1.g1 WHERE in1 = 5"); //$NON-NLS-1$
-        
-        // Construct command metadata
-        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5");  //$NON-NLS-1$
-        ArrayList sqParams = new ArrayList();
-        ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
-        in.setType(DataTypeManager.DefaultDataClasses.STRING);
-        sqParams.add(in);
-        Map externalMetadata = new HashMap();
-        externalMetadata.put(sqGroup, sqParams);
-                    
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-
-        // Verify results        
-        helpCheckFrom((Query)command, new String[] { "pm1.g1" });         //$NON-NLS-1$
-        Collection vars = getVariables(command);
-        assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
-    }
-
-    @Test public void testStoredQueryTransformationWithVariable3() throws Exception {
-        Command command = QueryParser.getQueryParser().parseCommand("SELECT * FROM pm1.g1 WHERE in1 = 5 UNION SELECT * FROM pm1.g1"); //$NON-NLS-1$
-
-        // Construct command metadata
-        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
-        ArrayList sqParams = new ArrayList();
-        ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
-        in.setType(DataTypeManager.DefaultDataClasses.STRING);
-        sqParams.add(in);
-        Map externalMetadata = new HashMap();
-        externalMetadata.put(sqGroup, sqParams);
-
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-
-        // Verify results
-        Collection vars = getVariables(command);
-        assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
-    }
-    
-    @Test public void testStoredQueryTransformationWithVariable4() throws Exception {
-        Command command = QueryParser.getQueryParser().parseCommand("EXEC pm1.sq2(pm1.sq2.in)"); //$NON-NLS-1$
-
-        // resolve
-        try {
-            // Construct command metadata
-            GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
-            ArrayList sqParams = new ArrayList();
-            ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
-            in.setType(DataTypeManager.DefaultDataClasses.STRING);
-            sqParams.add(in);
-            Map externalMetadata = new HashMap();
-            externalMetadata.put(sqGroup, sqParams);
-
-            QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-            
-            fail("Expected exception on invalid variable pm1.sq2.in"); //$NON-NLS-1$
-        } catch(QueryResolverException e) {
-        	assertEquals("Symbol pm1.sq2.\"in\" is specified with an unknown group context", e.getMessage()); //$NON-NLS-1$
-        } 
-    }
-
-    @Test public void testExec1() {
-        helpResolve("EXEC pm1.sq2('xyz')"); //$NON-NLS-1$
-    }
-
-    @Test public void testExec2() {
-        // implicity convert 5 to proper type
-        helpResolve("EXEC pm1.sq2(5)"); //$NON-NLS-1$
-    }
-    
-    @Test public void testExecNamedParam() {
-        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz")};//$NON-NLS-1$
-        helpResolveExec("EXEC pm1.sq2(\"in\" = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
-    }
-    
-    @Test public void testExecNamedParamDup() {
-        helpResolveException("EXEC pm1.sq2(\"in\" = 'xyz', \"in\" = 'xyz1')");//$NON-NLS-1$
-    }
-
-    /** Should get exception because param name is wrong. */
-    @Test public void testExecWrongParamName() {
-        helpResolveException("EXEC pm1.sq2(in1 = 'xyz')");//$NON-NLS-1$
-    }
-
-    @Test public void testExecNamedParams() {
-        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(5))};//$NON-NLS-1$
-        helpResolveExec("EXEC pm1.sq3(\"in\" = 'xyz', in2 = 5)", expectedParameterExpressions);//$NON-NLS-1$
-    }   
-    
-    /** try entering params out of order */
-    @Test public void testExecNamedParamsReversed() {
-        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(5))};//$NON-NLS-1$
-        helpResolveExec("EXEC pm1.sq3(in2 = 5, \"in\" = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
-    }    
-    
-    /** test omitting an optional parameter */
-    @Test public void testExecNamedParamsOptionalParam() {
-        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(null), new Constant("something")};//$NON-NLS-1$ //$NON-NLS-2$
-        helpResolveExec("EXEC pm1.sq3b(\"in\" = 'xyz', in3 = 'something')", expectedParameterExpressions);//$NON-NLS-1$
-    }    
-
-    /** test omitting a required parameter that has a default value */
-    @Test public void testExecNamedParamsOmitRequiredParamWithDefaultValue() {
-        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(666)), new Constant("YYZ")};//$NON-NLS-1$ //$NON-NLS-2$
-        StoredProcedure sp = helpResolveExec("EXEC pm1.sq3b(\"in\" = 'xyz', in2 = 666)", expectedParameterExpressions);//$NON-NLS-1$
-        assertEquals("EXEC pm1.sq3b(\"in\" => 'xyz', in2 => 666)", sp.toString());
-    }    
-    
-    @Test public void testExecNamedParamsOptionalParamWithDefaults() {
-        Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
-        //override the default value for the first parameter
-        expectedParameterExpressions[0] = new Constant("xyz"); //$NON-NLS-1$
-        helpResolveExec("EXEC pm1.sqDefaults(inString = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
-    }    
-
-    @Test public void testExecNamedParamsOptionalParamWithDefaultsCaseInsensitive() {
-        Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
-        //override the default value for the first parameter
-        expectedParameterExpressions[0] = new Constant("xyz"); //$NON-NLS-1$
-        helpResolveExec("EXEC pm1.sqDefaults(iNsTrInG = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
-    }    
-
-    /** try just a few named parameters, in no particular order */
-    @Test public void testExecNamedParamsOptionalParamWithDefaults2() {
-        Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
-        //override the proper default values in expected results
-        expectedParameterExpressions[3] = new Constant(Boolean.FALSE); 
-        expectedParameterExpressions[9] = new Constant(new Integer(666));
-        helpResolveExec("EXEC pm1.sqDefaults(ininteger = 666, inboolean={b'false'})", expectedParameterExpressions);//$NON-NLS-1$
-    }    
-
-    /** 
-     * Try entering in no actual parameters, rely entirely on defaults.  
-     * This also tests the default value transformation code in ExecResolver. 
-     */
-    @Test public void testExecNamedParamsOptionalParamWithAllDefaults() {
-        Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
-        helpResolveExec("EXEC pm1.sqDefaults()", expectedParameterExpressions);//$NON-NLS-1$
-    }     
-
-    /**
-     * Retrieve the Object array of expected default values for the stored procedure
-     * "pm1.sqDefaults" in FakeMetadataFactory.example1().
-     * @return
-     * @since 4.3
-     */
-    private Object[] helpGetStoredProcDefaultValues() {
-        
-        // This needs to match what's in FakeMetadataFactory.example1 for this stored proc
-        return new Object[]  {
-            new Constant("x"), //$NON-NLS-1$
-            new Constant(new BigDecimal("13.0")),//$NON-NLS-1$
-            new Constant(new BigInteger("13")),//$NON-NLS-1$
-            new Constant(Boolean.TRUE),
-            new Constant(new Byte("1")),//$NON-NLS-1$
-            new Constant(new Character('q')),
-            new Constant(Date.valueOf("2003-03-20")),//$NON-NLS-1$
-            new Constant(new Double(13.0)),
-            new Constant(new Float(13.0)),
-            new Constant(new Integer(13)),
-            new Constant(new Long(13)),
-            new Constant(new Short((short)13)),
-            new Constant(Timestamp.valueOf("2003-03-20 21:26:00.000000")),//$NON-NLS-1$
-            new Constant(Time.valueOf("21:26:00")),//$NON-NLS-1$
-        };
-    }
-    
-    /** Should get exception because there are two required params */
-    @Test public void testExceptionNotSupplyingRequiredParam() {
-        helpResolveException("EXEC pm1.sq3(in2 = 5)");//$NON-NLS-1$
-    }
-    
-    /** Should get exception because the default value in metadata is bad for input param */
-    @Test public void testExceptionBadDefaultValue() {
-        helpResolveException("EXEC pm1.sqBadDefault()");//$NON-NLS-1$
-    }
-    
-    @Test public void testExecWithForcedConvertOfStringToCorrectType() {
-        // force conversion of '5' to proper type (integer)
-        helpResolve("EXEC pm1.sq3('x', '5')"); //$NON-NLS-1$
-    }
-
-    /**
-     * True/false are consistently representable by integers
-     */
-    @Test public void testExecBadType() {
-        helpResolve("EXEC pm1.sq3('xyz', {b'true'})"); //$NON-NLS-1$
-    }
-    
-    @Test public void testSubqueryInUnion() {
-        String sql = "SELECT IntKey, FloatNum FROM BQT1.MediumA WHERE (IntKey >= 0) AND (IntKey < 15) " + //$NON-NLS-1$
-            "UNION ALL " + //$NON-NLS-1$
-            "SELECT BQT2.SmallB.IntKey, y.FloatNum " +  //$NON-NLS-1$
-            "FROM BQT2.SmallB INNER JOIN " + //$NON-NLS-1$
-            "(SELECT IntKey, FloatNum FROM BQT1.MediumA ) AS y ON BQT2.SmallB.IntKey = y.IntKey " + //$NON-NLS-1$
-            "WHERE (y.IntKey >= 10) AND (y.IntKey < 30) " + //$NON-NLS-1$
-            "ORDER BY IntKey, FloatNum";  //$NON-NLS-1$
-
-        helpResolve(sql, FakeMetadataFactory.exampleBQTCached(), null);
-    }
-
-    @Test public void testSubQueryINClause1(){
-		//select e1 from pm1.g1 where e2 in (select e2 from pm4.g1)
-
-		//sub command
-		Select innerSelect = new Select();
-		ElementSymbol e2inner = new ElementSymbol("e2"); //$NON-NLS-1$
-		innerSelect.addSymbol(e2inner);
-		From innerFrom = new From();
-		GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
-		innerFrom.addGroup(pm4g1);
-		Query innerQuery = new Query();
-		innerQuery.setSelect(innerSelect);
-		innerQuery.setFrom(innerFrom);
-		
-		//outer command
-		Select outerSelect = new Select();
-		ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
-    	outerSelect.addSymbol(e1);
-		From outerFrom = new From();
-    	GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
-		outerFrom.addGroup(pm1g1);
-    	ElementSymbol e2outer = new ElementSymbol("e2"); //$NON-NLS-1$
-		SubquerySetCriteria crit = new SubquerySetCriteria(e2outer, innerQuery);
-    	Query outerQuery = new Query();
-    	outerQuery.setSelect(outerSelect);
-    	outerQuery.setFrom(outerFrom);
-    	outerQuery.setCriteria(crit);
-    	
-    	//test
-    	helpResolve(outerQuery);
-
-    	helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-    	helpCheckFrom(innerQuery, new String[] { "pm4.g1" }); //$NON-NLS-1$
-    	helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
-    	helpCheckSelect(innerQuery, new String[] { "pm4.g1.e2" }); //$NON-NLS-1$
-    	helpCheckElements(outerQuery.getSelect(),
-    		new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
-    		new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
-    	helpCheckElements(innerQuery.getSelect(),
-    		new String[] { "pm4.g1.e2" }, //$NON-NLS-1$
-    		new String[] { "pm4.g1.e2" } ); //$NON-NLS-1$
-
-    	String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm4.g1)"; //$NON-NLS-1$
-    	assertEquals("Resolved string form was incorrect ", sql, outerQuery.toString()); //$NON-NLS-1$
-    }    
-
-	/**
-	 * An implicit type conversion needs to be inserted because the
-	 * project symbol of the subquery is not the same type as the expression in
-	 * the SubquerySetCriteria object
-	 */
-	@Test public void testSubQueryINClauseImplicitConversion(){
-		//select e1 from pm1.g1 where e2 in (select e1 from pm4.g1)
-	
-		//sub command
-		Select innerSelect = new Select();
-		ElementSymbol e1inner = new ElementSymbol("e1"); //$NON-NLS-1$
-		innerSelect.addSymbol(e1inner);
-		From innerFrom = new From();
-		GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
-		innerFrom.addGroup(pm4g1);
-		Query innerQuery = new Query();
-		innerQuery.setSelect(innerSelect);
-		innerQuery.setFrom(innerFrom);
-		
-		//outer command
-		Select outerSelect = new Select();
-		ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
-		outerSelect.addSymbol(e1);
-		From outerFrom = new From();
-		GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
-		outerFrom.addGroup(pm1g1);
-		ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
-		SubquerySetCriteria crit = new SubquerySetCriteria(e2, innerQuery);
-		Query outerQuery = new Query();
-		outerQuery.setSelect(outerSelect);
-		outerQuery.setFrom(outerFrom);
-		outerQuery.setCriteria(crit);
-		
-		//test
-		helpResolve(outerQuery);
-		
-		helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckFrom(innerQuery, new String[] { "pm4.g1" }); //$NON-NLS-1$
-		helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
-		helpCheckSelect(innerQuery, new String[] { "pm4.g1.e1" }); //$NON-NLS-1$
-		helpCheckElements(outerQuery.getSelect(),
-			new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
-			new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
-		helpCheckElements(innerQuery.getSelect(),
-			new String[] { "pm4.g1.e1" }, //$NON-NLS-1$
-			new String[] { "pm4.g1.e1" } ); //$NON-NLS-1$
-		
-		String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e1 FROM pm4.g1)"; //$NON-NLS-1$
-		assertEquals("Resolved string form was incorrect ", sql, outerQuery.toString()); //$NON-NLS-1$
-		
-		//make sure there is a convert function wrapping the criteria left expression
-		Collection functions = FunctionCollectorVisitor.getFunctions(outerQuery, true);
-		assertTrue(functions.size() == 1);
-		Function function = (Function)functions.iterator().next();
-		assertTrue(function.getName().equals(FunctionLibrary.CONVERT));
-		Expression[] args = function.getArgs();
-		assertSame(e2, args[0]);
-		assertTrue(args[1] instanceof Constant);		
-	}
-    
-	/**
-	 * Tests that resolving fails if there is no implicit conversion between the
-	 * type of the expression of the SubquerySetCriteria and the type of the
-	 * projected symbol of the subquery.
-	 */
-	@Test public void testSubQueryINClauseNoConversionFails(){
-		//select e1 from pm1.g1 where e1 in (select e2 from pm4.g1)
-
-		//sub command
-		Select innerSelect = new Select();
-		ElementSymbol e2inner = new ElementSymbol("e2"); //$NON-NLS-1$
-		innerSelect.addSymbol(e2inner);
-		From innerFrom = new From();
-		GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
-		innerFrom.addGroup(pm4g1);
-		Query innerQuery = new Query();
-		innerQuery.setSelect(innerSelect);
-		innerQuery.setFrom(innerFrom);
-
-		//outer command
-		Select outerSelect = new Select();
-		ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
-		outerSelect.addSymbol(e1);
-		From outerFrom = new From();
-		GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
-		outerFrom.addGroup(pm1g1);
-		SubquerySetCriteria crit = new SubquerySetCriteria(e1, innerQuery);
-		Query outerQuery = new Query();
-		outerQuery.setSelect(outerSelect);
-		outerQuery.setFrom(outerFrom);
-		outerQuery.setCriteria(crit);
-
-		//test
-		this.helpResolveFails(outerQuery);
-	}
-
-    @Test public void testSubQueryINClauseTooManyColumns(){
-        String sql = "select e1 from pm1.g1 where e1 in (select e1, e2 from pm4.g1)"; //$NON-NLS-1$
-
-        //test
-        this.helpResolveException(sql);
-    }
-
-	@Test public void testStoredQueryInFROMSubquery() {
-		String sql = "select X.e1 from (EXEC pm1.sq3('abc', 123)) as X"; //$NON-NLS-1$
-
-        helpResolve(sql);
-	}
-	
-	@Test public void testStoredQueryInINSubquery() throws Exception {
-		String sql = "select * from pm1.g1 where e1 in (EXEC pm1.sqsp1())"; //$NON-NLS-1$
-
-        helpResolve(sql);
-	}	
-    
-    @Test public void testIsXMLQuery1() throws Exception {
-        helpTestIsXMLQuery("SELECT * FROM pm1.g1", false);     //$NON-NLS-1$
-    }
-
-    @Test public void testIsXMLQuery2() throws Exception {
-        helpTestIsXMLQuery("SELECT * FROM xmltest.doc1", true); //$NON-NLS-1$
-    }
-
-    /**
-     * Must be able to resolve XML query if short doc name
-     * is used (assuming short doc name isn't ambiguous in a
-     * VDB).  Defect 11479.
-     */
-    @Test public void testIsXMLQuery3() throws Exception {
-        helpTestIsXMLQuery("SELECT * FROM doc1", true); //$NON-NLS-1$
-    }
-
-    @Test public void testIsXMLQueryFail1() throws Exception {
-        helpTestIsXMLQuery("SELECT * FROM xmltest.doc1, xmltest.doc2", false); //$NON-NLS-1$
-    }
-
-    @Test public void testIsXMLQueryFail2() throws Exception {
-        helpTestIsXMLQuery("SELECT * FROM xmltest.doc1, pm1.g1", false); //$NON-NLS-1$
-    }
-
-    @Test public void testIsXMLQueryFail3() throws Exception {
-        helpTestIsXMLQuery("SELECT * FROM pm1.g1, xmltest.doc1", false); //$NON-NLS-1$
-    }
-
-    /**
-     * "docA" is ambiguous as there exist two documents called
-     * xmlTest2.docA and xmlTest3.docA.  Defect 11479.
-     */
-    @Test public void testIsXMLQueryFail4() throws Exception {
-        Query query = (Query) helpParse("SELECT * FROM docA"); //$NON-NLS-1$
-
-        try {
-            QueryResolver.isXMLQuery(query, metadata);
-            fail("expected exception"); //$NON-NLS-1$
-        } catch (QueryResolverException e) {
-            assertEquals("Group specified is ambiguous, resubmit the query by fully qualifying the group name: docA", e.getMessage()); //$NON-NLS-1$
-        }
-    }
-    
-    @Test public void testStringConversion1() {
-		// Expected left expression
-        ElementSymbol e1 = new ElementSymbol("pm3.g1.e2"); //$NON-NLS-1$
-        e1.setType(DataTypeManager.DefaultDataClasses.DATE);
-      
-        // Expected right expression
-        Class srcType = DataTypeManager.DefaultDataClasses.STRING;
-        String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
-        Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
-        
-		FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();                         
-		FunctionDescriptor fd = library.findFunction(FunctionLibrary.CONVERT, new Class[] { srcType, DataTypeManager.DefaultDataClasses.STRING });
-
-		Function conversion = new Function(fd.getName(), new Expression[] { expression, new Constant(tgtTypeName) });
-		conversion.setType(DataTypeManager.getDataTypeClass(tgtTypeName));
-		conversion.setFunctionDescriptor(fd);
-		conversion.makeImplicit();
-		
-		// Expected criteria
-		CompareCriteria expected = new CompareCriteria();
-		expected.setLeftExpression(e1);
-		expected.setOperator(CompareCriteria.EQ);
-		expected.setRightExpression(conversion);
-         
-		// Resolve the query and check against expected objects
-		CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e2='2003-02-27'");	 //$NON-NLS-1$
-	
-		//if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
-		//	fail("left exprs not equal");
-		//} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
-		//	fail("right not equal");
-		//}
-		
-		assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
-    }
-		
-	@Test public void testStringConversion2() {
-		// Expected left expression
-		ElementSymbol e1 = new ElementSymbol("pm3.g1.e2"); //$NON-NLS-1$
-		e1.setType(DataTypeManager.DefaultDataClasses.DATE);
-      
-		// Expected right expression
-		Class srcType = DataTypeManager.DefaultDataClasses.STRING;
-		String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
-		Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
-        
-		FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();                        
-		FunctionDescriptor fd = library.findFunction(FunctionLibrary.CONVERT, new Class[] { srcType, DataTypeManager.DefaultDataClasses.STRING });
-
-		Function conversion = new Function(fd.getName(), new Expression[] { expression, new Constant(tgtTypeName) });
-		conversion.setType(DataTypeManager.getDataTypeClass(tgtTypeName));
-		conversion.setFunctionDescriptor(fd);
-		conversion.makeImplicit();
-		
-		// Expected criteria
-		CompareCriteria expected = new CompareCriteria();
-		expected.setLeftExpression(conversion);
-		expected.setOperator(CompareCriteria.EQ);
-		expected.setRightExpression(e1);
-         
-		// Resolve the query and check against expected objects
-		CompareCriteria actual = (CompareCriteria) helpResolveCriteria("'2003-02-27'=pm3.g1.e2");	 //$NON-NLS-1$
-	
-		//if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
-		//	fail("Left expressions not equal");
-		//} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
-		//	fail("Right expressions not equal");
-		//}
-		
-		assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
-	}		
-    
-    // special test for both sides are String
-	@Test public void testStringConversion3() {
-		// Expected left expression
-		ElementSymbol e1 = new ElementSymbol("pm3.g1.e1"); //$NON-NLS-1$
-		e1.setType(DataTypeManager.DefaultDataClasses.STRING);
-			   
-		// Expected right expression
-		Constant e2 = new Constant("2003-02-27"); //$NON-NLS-1$
-			   
-		// Expected criteria
-		CompareCriteria expected = new CompareCriteria();
-		expected.setLeftExpression(e1);
-		expected.setOperator(CompareCriteria.EQ);
-		expected.setRightExpression(e2);
-         
-		// Resolve the query and check against expected objects
-		CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e1='2003-02-27'");	 //$NON-NLS-1$
-		
-		//if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
-		//	System.out.println("left exprs not equal");
-		//} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
-		//	System.out.println("right exprs not equal");
-		//}
-		
-		assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
-	}	
-
-    @Test public void testDateToTimestampConversion_defect9747() {
-        // Expected left expression
-        ElementSymbol e1 = new ElementSymbol("pm3.g1.e4"); //$NON-NLS-1$
-        e1.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
-               
-        // Expected right expression
-        Constant e2 = new Constant(TimestampUtil.createDate(96, 0, 31), DataTypeManager.DefaultDataClasses.DATE);
-        Function f1 = new Function("convert", new Expression[] { e2, new Constant(DataTypeManager.DefaultDataTypes.TIMESTAMP)}); //$NON-NLS-1$
-        f1.makeImplicit();
-               
-        // Expected criteria
-        CompareCriteria expected = new CompareCriteria();
-        expected.setLeftExpression(e1);
-        expected.setOperator(CompareCriteria.GT);
-        expected.setRightExpression(f1);
-         
-        // Resolve the query and check against expected objects
-        CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e4 > {d '1996-01-31'}");    //$NON-NLS-1$
-        
-        assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
-    }   
-        
-    @Test public void testFailedConversion_defect9725() throws Exception{
-    	helpResolveException("select * from pm3.g1 where pm3.g1.e4 > {b 'true'}", "Error Code:ERR.015.008.0027 Message:The expressions in this criteria are being compared but are of differing types (timestamp and boolean) and no implicit conversion is available:  pm3.g1.e4 > TRUE"); //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-            
-    @Test public void testLookupFunction() {     
-        String sql = "SELECT lookup('pm1.g1', 'e1', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
-        Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "x", "y" }); //$NON-NLS-1$ //$NON-NLS-2$
-        helpCheckElements(resolvedQuery.getSelect(), 
-            new String[] { "PM1.G1.E2", "PM1.G1.E3" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { "PM1.G1.E2", "PM1.G1.E3" } ); //$NON-NLS-1$ //$NON-NLS-2$
-        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
-        
-        List projSymbols = resolvedQuery.getSelect().getProjectedSymbols();
-        assertEquals("Wrong number of projected symbols", 2, projSymbols.size()); //$NON-NLS-1$
-        assertEquals("Wrong type for first symbol", String.class, ((SingleElementSymbol)projSymbols.get(0)).getType()); //$NON-NLS-1$
-        assertEquals("Wrong type for second symbol", Double.class, ((SingleElementSymbol)projSymbols.get(1)).getType()); //$NON-NLS-1$
-    }
-
-    @Test public void testLookupFunctionFailBadElement() {     
-        String sql = "SELECT lookup('nosuch', 'elementhere', 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
-        helpResolveException(sql);
-    }
-
-    @Test public void testLookupFunctionFailNotConstantArg1() {     
-        String sql = "SELECT lookup(e1, 'e1', 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
-        helpResolveException(sql);
-    }
-
-    @Test public void testLookupFunctionFailNotConstantArg2() {     
-        String sql = "SELECT lookup('pm1.g1', e1, 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
-        helpResolveException(sql);
-    }
-   		
-    @Test public void testLookupFunctionFailNotConstantArg3() {     
-        String sql = "SELECT lookup('pm1.g1', 'e1', e1, e2) AS x FROM pm1.g1"; //$NON-NLS-1$
-        helpResolveException(sql);
-    }
- 
-	@Test public void testLookupFunctionVirtualGroup() throws Exception {     
-		String sql = "SELECT lookup('vm1.g1', 'e1', 'e2', e2)  FROM vm1.g1 "; //$NON-NLS-1$
-		Query command = (Query) helpParse(sql);
-		QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());  		
-	}
-	
-	@Test public void testLookupFunctionPhysicalGroup() throws Exception {     
-		String sql = "SELECT lookup('pm1.g1', 'e1', 'e2', e2)  FROM pm1.g1 "; //$NON-NLS-1$
-		Query command = (Query) helpParse(sql);
-		QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
-	}
-	
-    @Test public void testLookupFunctionFailBadKeyElement() throws Exception {
-    	String sql = "SELECT lookup('pm1.g1', 'e1', 'x', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
-    	Command command = QueryParser.getQueryParser().parseCommand(sql);
-    	try {
-    		QueryResolver.resolveCommand(command, metadata);
-    		fail("exception expected"); //$NON-NLS-1$
-    	} catch (QueryResolverException e) {
-    		
-    	}
-    }
-    
-	@Test public void testNamespacedFunction() throws Exception {     
-		String sql = "SELECT namespace.func('e1')  FROM vm1.g1 "; //$NON-NLS-1$
-
-        FunctionLibrary funcLibrary = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree(new UDFSource(new FakeFunctionMetadataSource().getFunctionMethods())));
-        FakeMetadataFacade metadata = new FakeMetadataFacade(FakeMetadataFactory.example1Cached().getStore(), funcLibrary);
-		
-		Query command = (Query) helpParse(sql);
-		QueryResolver.resolveCommand(command, metadata);
-		
-		command = (Query) helpParse("SELECT func('e1')  FROM vm1.g1 ");
-		QueryResolver.resolveCommand(command, metadata);  		
-		
-	}    
-    
-    // special test for both sides are String
-    @Test public void testSetCriteriaCastFromExpression_9657() {
-        // parse
-        Criteria expected = null;
-        Criteria actual = null;
-        try { 
-            actual = QueryParser.getQueryParser().parseCriteria("bqt1.smalla.shortvalue IN (1, 2)"); //$NON-NLS-1$
-            expected = QueryParser.getQueryParser().parseCriteria("convert(bqt1.smalla.shortvalue, integer) IN (1, 2)"); //$NON-NLS-1$
-           
-        } catch(TeiidException e) { 
-            fail("Exception during parsing (" + e.getClass().getName() + "): " + e.getMessage());    //$NON-NLS-1$ //$NON-NLS-2$
-        }   
-   
-        // resolve
-        try { 
-            QueryResolver.resolveCriteria(expected, FakeMetadataFactory.exampleBQTCached());
-            QueryResolver.resolveCriteria(actual, FakeMetadataFactory.exampleBQTCached());
-        } catch(TeiidException e) { 
-            fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        } 
-        
-        // Tweak expected to hide convert function - this is expected
-        ((Function) ((SetCriteria)expected).getExpression()).makeImplicit();
-        
-        assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
-    }    
-    
-    /** select e1 from pm1.g1 where e2 BETWEEN 1000 AND 2000 */
-    @Test public void testBetween1(){
-        String sql = "select e1 from pm1.g1 where e2 BETWEEN 1000 AND 2000"; //$NON-NLS-1$
-        helpResolve(sql);
-    } 
-
-    /** select e1 from pm1.g1 where e2 NOT BETWEEN 1000 AND 2000 */
-    @Test public void testBetween2(){
-        String sql = "select e1 from pm1.g1 where e2 NOT BETWEEN 1000 AND 2000"; //$NON-NLS-1$
-        helpResolve(sql);
-    } 
-
-    /** select e2 from pm1.g1 where e4 BETWEEN 1000 AND e2 */
-    @Test public void testBetween3(){
-        String sql = "select e2 from pm1.g1 where e4 BETWEEN 1000 AND e2"; //$NON-NLS-1$
-        helpResolve(sql);
-    } 
-
-    /** select e2 from pm1.g1 where e2 BETWEEN 1000 AND e4 */
-    @Test public void testBetween4(){
-        String sql = "select e2 from pm1.g1 where e2 BETWEEN 1000 AND e4"; //$NON-NLS-1$
-        helpResolve(sql);
-    } 
-
-    /** select e1 from pm1.g1 where 1000 BETWEEN e1 AND e2 */
-    @Test public void testBetween5(){
-        String sql = "select e1 from pm1.g1 where 1000 BETWEEN e1 AND e2"; //$NON-NLS-1$
-        helpResolve(sql);
-    } 
-
-    /** select e1 from pm1.g1 where 1000 BETWEEN e2 AND e1 */
-    @Test public void testBetween6(){
-        String sql = "select e1 from pm1.g1 where 1000 BETWEEN e2 AND e1"; //$NON-NLS-1$
-        helpResolve(sql);
-    } 
-
-    /** select e1 from pm3.g1 where e2 BETWEEN e3 AND e4 */
-    @Test public void testBetween7(){
-        String sql = "select e1 from pm3.g1 where e2 BETWEEN e3 AND e4"; //$NON-NLS-1$
-        helpResolve(sql);
-    } 
-
-    /** select pm3.g1.e1 from pm3.g1, pm3.g2 where pm3.g1.e4 BETWEEN pm3.g1.e2 AND pm3.g2.e2 */
-    @Test public void testBetween8(){
-        String sql = "select pm3.g1.e1 from pm3.g1, pm3.g2 where pm3.g1.e4 BETWEEN pm3.g1.e2 AND pm3.g2.e2"; //$NON-NLS-1$
-        helpResolve(sql);
-    } 
-
-    /** select e1 from pm1.g1 where e2 = any (select e2 from pm4.g1) */
-    @Test public void testCompareSubQuery1(){
-
-        String sql = "select e1 from pm1.g1 where e2 = any (select e2 from pm4.g1)"; //$NON-NLS-1$
-        Query outerQuery = (Query) this.helpResolveSubquery(sql, new String[0]);
-
-        helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-        helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
-        helpCheckElements(outerQuery.getSelect(),
-            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
-            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
-//        helpCheckFrom(innerQuery, new String[] { "pm4.g1" });
-//        helpCheckSelect(innerQuery, new String[] { "pm4.g1.e2" });
-//        helpCheckElements(innerQuery.getSelect(),
-//            new String[] { "pm4.g1.e2" },
-//            new String[] { "pm4.g1.e2" } );
-
-        String sqlActual = "SELECT e1 FROM pm1.g1 WHERE e2 = ANY (SELECT e2 FROM pm4.g1)"; //$NON-NLS-1$
-        assertEquals("Resolved string form was incorrect ", sqlActual, outerQuery.toString()); //$NON-NLS-1$
-    }    
-
-    /** select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1) */
-    @Test public void testCompareSubQuery2(){
-        String sql = "select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    } 
-
-    /** select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3') */
-    @Test public void testCompareSubQuery3(){
-        String sql = "select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3')"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    } 
-
-    /** select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3') */
-    @Test public void testCompareSubQueryImplicitConversion(){
-        String sql = "select e1 from pm1.g1 where e1 < (select e2 from pm4.g1 where e1 = '3')"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    } 
-
-    @Test public void testExistsSubQuery(){
-        String sql = "select e1 from pm1.g1 where exists (select e2 from pm4.g1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    } 
-
-    @Test public void testExistsSubQuery2(){
-        String sql = "select e1 from pm1.g1 where exists (select e1, e2 from pm4.g1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    } 
-
-    @Test public void testScalarSubQueryInSelect(){
-        String sql = "select e1, (select e2 from pm4.g1 where e1 = '3') from pm1.g1"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    } 
-
-    @Test public void testScalarSubQueryInSelect2(){
-        String sql = "select (select e2 from pm4.g1 where e1 = '3'), e1 from pm1.g1"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    } 
-
-    @Test public void testScalarSubQueryInSelectWithAlias(){
-        String sql = "select e1, (select e2 from pm4.g1 where e1 = '3') as X from pm1.g1"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    } 
-
-    @Test public void testSelectWithNoFrom() {
-        String sql = "SELECT 5"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testSelectWithNoFrom_Alias() {
-        String sql = "SELECT 5 AS INTKEY"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testSelectWithNoFrom_Alias_OrderBy() {
-        String sql = "SELECT 5 AS INTKEY ORDER BY INTKEY"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testSubqueryCorrelatedInCriteria(){
-        String sql = "select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1 where pm1.g1.e1 = pm4.g1.e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"pm1.g1.e1"}); //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryCorrelatedInCriteria2(){
-        String sql = "select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1 where pm1.g1.e1 = e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"pm1.g1.e1"}); //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryCorrelatedInCriteria3(){
-        String sql = "select e1 from pm1.g1 X where e2 = all (select e2 from pm4.g1 where X.e1 = pm4.g1.e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
-    }
-    
-    @Test public void testSubqueryCorrelatedInCriteria4(){
-        String sql = "select e2 from pm1.g1 X where e2 in (select e2 from pm1.g1 Y where X.e1 = Y.e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
-    }    
-
-    @Test public void testSubqueryCorrelatedInCriteria5(){
-        String sql = "select e1 from pm1.g1 X where e2 = all (select e2 from pm1.g1 Y where X.e1 = e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
-    }    
-
-    /* 'e5' is only in pm4.g2 */
-    @Test public void testSubqueryCorrelatedInCriteria6(){
-        String sql = "select e1 from pm4.g2 where e2 = some (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
-    }
-
-    /* 'e5' is only in pm4.g2 */
-    @Test public void testSubqueryCorrelatedInCriteria7(){
-        String sql = "select e1 from pm4.g2 where exists (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryCorrelatedInHaving(){
-        String sql = "select e1, e2 from pm4.g2 group by e2 having e2 in (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryCorrelatedInHaving2(){
-        String sql = "select e1, e2 from pm4.g2 group by e2 having e2 <= all (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
-    }
-
-    /* 'e5' is only in pm4.g2 */
-    @Test public void testSubqueryCorrelatedInSelect(){
-        String sql = "select e1, (select e2 from pm4.g1 where e5 = e1) from pm4.g2"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryCorrelatedInSelect2(){
-        String sql = "select e1, (select e2 from pm4.g1 where pm4.g2.e5 = e1) from pm4.g2"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryCorrelatedInSelect3(){
-        String sql = "select e1, (select e2 from pm4.g1 Y where X.e5 = Y.e1) from pm4.g2 X"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"X.e5"}); //$NON-NLS-1$
-    }
-
-    /* 'e5' is only in pm4.g2 */
-    @Test public void testNestedCorrelatedSubqueries(){
-        String sql = "select e1, (select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1 where e5 = e1)) from pm4.g2"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
-    }
-
-    /**
-     * 'e5' is in pm4.g2, so it will be resolved to the group aliased as 'Y'
-     */
-    @Test public void testNestedCorrelatedSubqueries2(){
-        String sql = "select e1, (select e2 from pm4.g2 Y where e2 = all (select e2 from pm4.g1 where e5 = e1)) from pm4.g2 X"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"Y.e5"}); //$NON-NLS-1$
-    }
-
-    /**
-     *  'e5' is in pm4.g2; it will be resolved to the group aliased as 'X' 
-     */
-    @Test public void testNestedCorrelatedSubqueries3(){
-        String sql = "select e1, (select e2 from pm4.g2 Y where e2 = all (select e2 from pm4.g1 where X.e5 = e1)) from pm4.g2 X"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"X.e5"}); //$NON-NLS-1$
-    }
-
-    /**
-     *  'e5' is in X and Y 
-     */
-    @Test public void testNestedCorrelatedSubqueries4(){
-        String sql = "select X.e2 from pm4.g2 Y, pm4.g2 X where X.e2 = all (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
-        helpResolveException(sql, metadata, "Element \"e5\" is ambiguous, it exists in two or more groups."); //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryCorrelatedInCriteriaVirtualLayer(){
-        String sql = "select e2 from vm1.g1 where e2 = all (select e2 from vm1.g2 where vm1.g1.e1 = vm1.g2.e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"vm1.g1.e1"}); //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryCorrelatedInCriteriaVirtualLayer2(){
-        String sql = "select e2 from vm1.g1 X where e2 = all (select e2 from vm1.g2 where X.e1 = vm1.g2.e1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
-    }
-
-    /** 
-     * Although this query makes no sense, the "e1" in the nested criteria is
-     * NOT a correlated reference 
-     */
-    @Test public void testSubqueryNonCorrelatedInCriteria(){
-        String sql = "select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    }
-
-    /** 
-     * Although this query makes no sense, the "e1" in the nested criteria is
-     * NOT a correlated reference 
-     */
-    @Test public void testSubqueryNonCorrelatedInCriteria2(){
-        String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1))"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    }
-
-    /** 
-     * Although this query makes no sense, the "e1" in the nested criteria is
-     * NOT a correlated reference 
-     */
-    @Test public void testSubqueryNonCorrelatedInCriteria3(){
-        String sql = "SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    }
-
-    /** 
-     * The group pm1.g1 in the FROM clause of the subquery should resolve to the 
-     * group in metadata, not the temporary child metadata group defined by the
-     * outer query.
-     */
-    @Test public void testSubquery_defect10090(){
-        String sql = "select pm1.g1.e1 from pm1.g1 where pm1.g1.e2 in (select pm1.g1.e2 from pm1.g1 where pm1.g1.e4 = 2.0)";  //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    }
-
-    /**
-     * Workaround is to alias group in FROM of outer query (aliasing subquery group doesn't work)
-     */
-    @Test public void testSubquery_defect10090Workaround(){
-        String sql = "select X.e1 from pm1.g1 X where X.e2 in (select pm1.g1.e2 from pm1.g1 where pm1.g1.e4 = 2.0)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    }
-
-    @Test public void testSubquery2_defect10090(){
-        String sql = "select pm1.g1.e1 from pm1.g1 where pm1.g1.e2 in (select X.e2 from pm1.g1 X where X.e4 = 2.0)"; //$NON-NLS-1$
-        this.helpResolveSubquery(sql, new String[0]);
-    }
-    
-    /** test jdbc USER method */
-    @Test public void testUser() {
-        //String sql = "select intkey from SmallA where user() = 'bqt2'";
-
-        // Expected left expression
-        FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();                          
-        FunctionDescriptor fd = library.findFunction(FunctionLibrary.USER, new Class[] { });
-        Function user = new Function(fd.getName(), new Expression[] {});
-        user.setFunctionDescriptor(fd);
-
-        // Expected criteria
-        CompareCriteria expected = new CompareCriteria();
-        // Expected right expression
-        Expression e1 = new Constant("bqt2", String.class); //$NON-NLS-1$
-        // Expected left expression
-        expected.setLeftExpression(user);
-        expected.setOperator(CompareCriteria.EQ);
-        expected.setRightExpression(e1);
-         
-        // Resolve the query and check against expected objects
-        CompareCriteria actual = (CompareCriteria) helpResolveCriteria("user()='bqt2'");    //$NON-NLS-1$
-        assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
-    }
-    
-    @Test public void testCaseExpression1() {
-        String sql = "SELECT e1, CASE e2 WHEN 0 THEN 20 WHEN 1 THEN 21 WHEN 2 THEN 500 END AS testElement FROM pm1.g1" //$NON-NLS-1$
-                    +" WHERE e1 = CASE WHEN e2 = 0 THEN 'a' WHEN e2 = 1 THEN 'b' ELSE 'c' END"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    
-    @Test public void testCaseExpression2() {
-        // nested case expressions
-        String sql = "SELECT CASE e2" + //$NON-NLS-1$
-                                " WHEN 0 THEN CASE e1 " + //$NON-NLS-1$
-                                                " WHEN 'a' THEN 100" + //$NON-NLS-1$
-                                                " WHEN 'b' THEN 200 " + //$NON-NLS-1$
-                                                " ELSE 1000 " + //$NON-NLS-1$
-                                            " END" + //$NON-NLS-1$
-                                " WHEN 1 THEN 21" + //$NON-NLS-1$
-                                " WHEN (CASE WHEN e1 = 'z' THEN 2 WHEN e1 = 'y' THEN 100 ELSE 3 END) THEN 500" + //$NON-NLS-1$
-                           " END AS testElement FROM pm1.g1"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testCaseExpressionWithNestedFunction() {
-        String sql = "SELECT CASE WHEN e2 < 0 THEN abs(CASE WHEN e2 < 0 THEN -1 ELSE e2 END)" + //$NON-NLS-1$
-                           " ELSE e2 END FROM pm1.g1"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testFunctionWithNestedCaseExpression() {
-        String sql = "SELECT abs(CASE e1 WHEN 'testString1' THEN -13" + //$NON-NLS-1$
-                                       " WHEN 'testString2' THEN -5" + //$NON-NLS-1$
-                                       " ELSE abs(e2)" + //$NON-NLS-1$
-                               " END) AS absVal FROM pm1.g1"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
- 
-    @Test public void testDefect10809(){
-        String sql = "select * from LOB_TESTING_ONE where CLOB_COLUMN LIKE '%fff%'"; //$NON-NLS-1$
-        helpResolve(helpParse(sql), FakeMetadataFactory.exampleBQTCached(), AnalysisRecord.createNonRecordingRecord());
-    }
-    
-    @Test public void testNonAutoConversionOfLiteralIntegerToShort() throws Exception {       
-        // parse
-        Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE shortvalue = 5"); //$NON-NLS-1$
-        
-        // resolve
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
-        
-        // Check whether an implicit conversion was added on the correct side
-        CompareCriteria crit = (CompareCriteria) command.getCriteria();
-         
-        assertEquals(DataTypeManager.DefaultDataClasses.SHORT, crit.getRightExpression().getType());
-        assertEquals("Sql is incorrect after resolving", "SELECT intkey FROM bqt1.smalla WHERE shortvalue = 5", command.toString()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testNonAutoConversionOfLiteralIntegerToShort2() throws Exception {       
-        // parse
-        Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE 5 = shortvalue"); //$NON-NLS-1$
-        
-        // resolve
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
-        
-        // Check whether an implicit conversion was added on the correct side
-        CompareCriteria crit = (CompareCriteria) command.getCriteria();
-         
-        assertEquals(DataTypeManager.DefaultDataClasses.SHORT, crit.getLeftExpression().getType());
-        assertEquals("Sql is incorrect after resolving", "SELECT intkey FROM bqt1.smalla WHERE 5 = shortvalue", command.toString()); //$NON-NLS-1$ //$NON-NLS-2$
-    }               
-
-    @Test public void testAliasedOrderBy() {
-        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1 as y FROM pm1.g1 ORDER BY y"); //$NON-NLS-1$
-        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "y" }); //$NON-NLS-1$
-    }        
-    
-    @Test public void testUnaliasedOrderBySucceeds() {
-        helpResolve("SELECT pm1.g1.e1 a, pm1.g1.e1 b FROM pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
-    }
-    
-    @Test public void testUnaliasedOrderBySucceeds1() {
-        helpResolve("SELECT pm1.g1.e1 a FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
-    }
-    
-    @Test public void testUnaliasedOrderByFails() {
-        helpResolveException("SELECT pm1.g1.e1 e2 FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e2"); //$NON-NLS-1$
-    }
-    
-    @Test public void testUnaliasedOrderByFails1() {
-        helpResolveException("SELECT pm1.g1.e1 e2 FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e2 + 1"); //$NON-NLS-1$
-    }
-
-    /** 
-     * the group g1 is not known to the order by clause of a union
-     */
-    @Test public void testUnionOrderByFail() {
-        helpResolveException("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY g1.e1", "ORDER BY expression 'g1.e1' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
-    }      
-    
-    @Test public void testUnionOrderByFail1() {
-        helpResolveException("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g1.e1", "ORDER BY expression 'pm1.g1.e1' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testOrderByPartiallyQualified() {
-        helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY g1.e1"); //$NON-NLS-1$
-    }
-    
-    /** 
-     * the group g1 is not known to the order by clause of a union
-     */
-    @Test public void testUnionOrderBy() {
-        helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY e1"); //$NON-NLS-1$
-    } 
-    
-    /** 
-     * Test for defect 12087 - Insert with implicit conversion from integer to short
-     */
-    @Test public void testImplConversionBetweenIntAndShort() throws Exception {       
-    	Insert command = (Insert)QueryParser.getQueryParser().parseCommand("Insert into pm5.g3(e2) Values(100)"); //$NON-NLS-1$
-        QueryResolver.resolveCommand(command, metadata);
-        assertTrue(((Expression)command.getValues().get(0)).getType() == DataTypeManager.DefaultDataClasses.SHORT);
-    }
-    
-    public static FakeMetadataFacade example_12968() { 
-        // Create models
-        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("myModel"); //$NON-NLS-1$
-        FakeMetadataObject pm2 = FakeMetadataFactory.createPhysicalModel("myModel2"); //$NON-NLS-1$
-        
-        FakeMetadataObject pm1g1 = FakeMetadataFactory.createPhysicalGroup("myModel.myTable", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm2g1 = FakeMetadataFactory.createPhysicalGroup("myModel2.mySchema.myTable2", pm2); //$NON-NLS-1$
-        
-        List pm1g1e = FakeMetadataFactory.createElements(pm1g1, 
-            new String[] { "myColumn", "myColumn2" }, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List pm2g1e = FakeMetadataFactory.createElements(pm2g1, 
-            new String[] { "myColumn", "myColumn2" }, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);     
-        store.addObjects(pm1g1e);
-        store.addObject(pm2g1);     
-        store.addObjects(pm2g1e);
-        
-        return new FakeMetadataFacade(store);
-    }
-        
-    @Test public void testDefect12968_union() {
-        helpResolve(
-            helpParse("SELECT myModel.myTable.myColumn AS myColumn from myModel.myTable UNION " + //$NON-NLS-1$
-                "SELECT convert(null, string) AS myColumn From myModel2.mySchema.myTable2"),  //$NON-NLS-1$
-            example_12968(), AnalysisRecord.createNonRecordingRecord());
-    }
-
-
-    @Test public void testUnionQueryWithNull() throws Exception{
-    	helpResolve("SELECT NULL, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
-    	helpResolve("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT NULL, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
-    	helpResolve("SELECT e1, NULL FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
-    	helpResolve("SELECT e1, NULL FROM pm1.g2 UNION ALL SELECT e1, NULL FROM pm1.g3"); //$NON-NLS-1$
-    	helpResolve("SELECT e1, NULL as e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
-    	helpResolve("SELECT e1, NULL as e2 FROM pm1.g1 UNION ALL SELECT e1, e3 FROM pm1.g2"); //$NON-NLS-1$
-    }
-    
-    @Test public void testUnionQueryWithDiffTypes() throws Exception{
-        helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2"); //$NON-NLS-1$
-        helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2 UNION ALL SELECT NULL, e3 FROM pm1.g2");      //$NON-NLS-1$
-        helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e3, e3 FROM pm1.g2 UNION ALL SELECT NULL, e3 FROM pm1.g2");      //$NON-NLS-1$
-        helpResolve("SELECT e1, e2 FROM pm1.g3 UNION ALL SELECT MAX(e4), e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
-        helpResolve("SELECT e1, e4 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2"); //$NON-NLS-1$
-        helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
-        helpResolve("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e3, e4 FROM pm1.g2");   //$NON-NLS-1$
-        helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g2");  //$NON-NLS-1$
-        helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e1, e2 FROM pm1.g2"); //$NON-NLS-1$
-        helpResolve("SELECT MAX(e4), e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
-        //chooses a common type
-        helpResolve("select e2 from pm3.g1 union select e3 from pm3.g1 union select e4 from pm3.g1"); //$NON-NLS-1$
-    } 
-    
-    @Test public void testUnionQueryWithDiffTypesFails() throws Exception{
-        helpResolveException("SELECT e1 FROM pm1.g1 UNION (SELECT e2 FROM pm1.g2 UNION SELECT e2 from pm1.g1 order by e2)", "The Expression e2 used in a nested UNION ORDER BY clause cannot be implicitly converted from type integer to type string."); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testNestedUnionQueryWithNull() throws Exception{
-        SetQuery command = (SetQuery)helpResolve("SELECT e2, e3 FROM pm1.g1 UNION (SELECT null, e3 FROM pm1.g2 UNION SELECT null, e3 from pm1.g1)"); //$NON-NLS-1$
-        
-        assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(0)).getType());
-    }
-    
-    @Test public void testUnionQueryClone() throws Exception{
-        SetQuery command = (SetQuery)helpResolve("SELECT e2, e3 FROM pm1.g1 UNION SELECT e3, e2 from pm1.g1"); //$NON-NLS-1$
-        
-        assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(1)).getType());
-        
-        command = (SetQuery)command.clone();
-        
-        assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(1)).getType());
-    }
-    
-    @Test public void testSelectIntoNoFrom() {
-        helpResolve("SELECT 'a', 19, {b'true'}, 13.999 INTO pm1.g1"); //$NON-NLS-1$
-    }
-    
-    @Test public void testSelectInto() {
-        helpResolve("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2"); //$NON-NLS-1$
-    }
-    
-    @Test public void testSelectIntoTempGroup() {
-        helpResolve("SELECT 'a', 19, {b'true'}, 13.999 INTO #myTempTable"); //$NON-NLS-1$
-        helpResolve("SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g1"); //$NON-NLS-1$
-    }
-                
-    //procedural relational mapping
-    @Test public void testProcInVirtualGroup1(){
-        String sql = "select e1 from pm1.vsp26 where param1=1 and param2='a'"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testProcInVirtualGroup2(){
-        String sql = "select * from pm1.vsp26 as p where param1=1 and param2='a'"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testProcInVirtualGroup3(){
-        String sql = "SELECT P.e1 as ve3 FROM pm1.vsp26 as P, pm1.g2 where P.e1=g2.e1 and param1=1 and param2='a'"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testProcInVirtualGroup4(){
-        String sql = "SELECT P.e1 as ve3 FROM pm1.vsp26 as P, vm1.g1 where P.e1=g1.e1 and param1=1 and param2='a'"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testProcInVirtualGroup5(){
-        String sql = "SELECT * FROM (SELECT p.* FROM pm1.vsp26 as P, vm1.g1 where P.e1=g1.e1) x where param1=1 and param2='a'"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testProcInVirtualGroup6(){
-        String sql = "SELECT P.e1 as ve3, P.e2 as ve4 FROM pm1.vsp26 as P where param1=1 and param2='a'"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-
-    @Test public void testProcInVirtualGroup7(){
-        String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P where param1=1 and param2='a'"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-
-    @Test public void testProcInVirtualGroup7a(){
-        String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P where param1=1"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-        
-    @Test public void testProcParamComparison_defect13653() {
-        String userSql = "SELECT * FROM (EXEC mmspTest1.MMSP5('a')) AS a, (EXEC mmsptest1.mmsp6('b')) AS b"; //$NON-NLS-1$
-        
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-        AnalysisRecord analysis = AnalysisRecord.createNonRecordingRecord();
-        
-        Query query = (Query) helpResolve(userSql, metadata, analysis);
-        From from = query.getFrom();
-        Collection fromClauses = from.getClauses();
-        SPParameter params[] = new SPParameter[2];
-        Iterator iter = fromClauses.iterator();
-        while(iter.hasNext()) {
-            SubqueryFromClause clause = (SubqueryFromClause) iter.next();
-            StoredProcedure proc = (StoredProcedure) clause.getCommand();
-            List procParams = proc.getParameters();
-            for(int i=0; i<procParams.size(); i++) {
-                SPParameter param = (SPParameter) procParams.get(i);
-                if(param.getParameterType() == ParameterInfo.IN) {
-                    if(params[0] == null) {
-                        params[0] = param;
-                    } else {
-                        params[1] = param;
-                    }
-                }
-            }
-        }
-        
-        assertTrue("Params should be not equal", ! params[0].equals(params[1])); //$NON-NLS-1$
-    }
-    
-    @Test public void testNullConstantInSelect() throws Exception {
-        String userSql = "SELECT null as x"; //$NON-NLS-1$
-        Query query = (Query)helpParse(userSql);
-        
-        QueryResolver.resolveCommand(query, FakeMetadataFactory.exampleBQTCached(), AnalysisRecord.createNonRecordingRecord());
-        
-        // Check type of resolved null constant
-        SingleElementSymbol symbol = (SingleElementSymbol) query.getSelect().getSymbols().get(0);
-        assertNotNull(symbol.getType());
-        assertEquals(DataTypeManager.DefaultDataClasses.STRING, symbol.getType());
-    }
-
-    @Test public void test11716() throws Exception {
-    	String sql = "SELECT e1 FROM pm1.g1 where e1='1'"; //$NON-NLS-1$
-    	Map externalMetadata = new HashMap();
-    	GroupSymbol inputSet = new GroupSymbol("INPUT"); //$NON-NLS-1$
-    	List inputSetElements = new ArrayList();
-    	ElementSymbol inputSetElement = new ElementSymbol("INPUT.e1"); //$NON-NLS-1$
-    	inputSetElements.add(inputSetElement);
-    	externalMetadata.put(inputSet, inputSetElements);
-        Query command = (Query)helpParse(sql);
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-        Collection groups = GroupCollectorVisitor.getGroups(command, false);
-        assertFalse(groups.contains(inputSet));
-    }
-    
-    @Test public void testDefect15872() throws Exception {
-    	String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
-    		+ "BEGIN " //$NON-NLS-1$
-			+"SELECT * FROM pm1.g1 where model.table.param=e1; " //$NON-NLS-1$
-			+"end "; //$NON-NLS-1$
-        Command command = helpParse(sql);
-    	Map externalMetadata = new HashMap();
-    	GroupSymbol procGroup = new GroupSymbol("model.table"); //$NON-NLS-1$
-    	List procPrarms = new ArrayList();
-    	ElementSymbol param = new ElementSymbol("model.table.param"); //$NON-NLS-1$
-    	param.setType(String.class);
-    	procPrarms.add(param);
-    	externalMetadata.put(procGroup, procPrarms);
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-        CreateUpdateProcedureCommand proc = (CreateUpdateProcedureCommand)command;
-        Query query = (Query)proc.getSubCommands().get(0);
-        ElementSymbol inElement = (ElementSymbol)((CompareCriteria)query.getCriteria()).getLeftExpression();
-        assertNotNull("Input parameter does not have group", inElement.getGroupSymbol()); //$NON-NLS-1$
-    }
-    
-    @Test public void testInputToInputsConversion() 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 + "ROWS_UPDATED = (Select pm1.g1.e2 from pm1.g1 where e2=INPUTS.e2);\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
-        
-        Command command = helpResolveUpdateProcedure(procedure, userUpdateStr);
-        assertEquals("CREATE PROCEDURE\nBEGIN\nDECLARE integer var1;\nROWS_UPDATED = (SELECT pm1.g1.e2 FROM pm1.g1 WHERE e2 = INPUTS.e2);\nEND", command.toString());
-    }
-    
-    @Test public void testDefect16894_resolverException_1() {
-        helpResolve("SELECT * FROM (SELECT * FROM Pm1.g1 AS Y) AS X"); //$NON-NLS-1$
-    }
-
-    @Test public void testDefect16894_resolverException_2() {
-        helpResolve("SELECT * FROM (SELECT * FROM Pm1.g1) AS X"); //$NON-NLS-1$
-    }
-
-    @Test public void testDefect17385() throws Exception{  
-		String sql = "select e1 as x ORDER BY x"; //$NON-NLS-1$      
-		helpResolveException(sql);
-	}
-    
-    @Test public void testValidFullElementNotInQueryGroups() {
-        helpResolveException("select pm1.g1.e1 FROM pm1.g1 g"); //$NON-NLS-1$
-    }
-    
-    @Test public void testUnionInSubquery() throws Exception {
-        String sql = "SELECT StringKey FROM (SELECT BQT2.SmallB.StringKey FROM BQT2.SmallB union SELECT convert(BQT2.SmallB.FloatNum, string) FROM BQT2.SmallB) x";  //$NON-NLS-1$
-        Command command = QueryParser.getQueryParser().parseCommand(sql);
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
-    }
-
-    @Test public void testParameterError() throws Exception {
-        helpResolveException("EXEC pm1.sp2(1, 2)", metadata, "Error Code:ERR.015.008.0007 Message:Incorrect number of parameters specified on the stored procedure pm1.sp2 - expected 1 but got 2"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testUnionOfAliasedLiteralsGetsModified() {
-        String sql = "SELECT 5 AS x UNION ALL SELECT 10 AS x"; //$NON-NLS-1$
-        Command c = helpResolve(sql); 
-        assertEquals(sql, c.toString());
-    }
-    
-    @Test public void testXMLWithProcSubquery() {
-        String sql = "SELECT * FROM xmltest.doc4 WHERE node2 IN (SELECT e1 FROM (EXEC pm1.vsp1()) AS x)"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        assertEquals(sql, c.toString());
-    }
-    
-    @Test public void testDefect18832() {
-        String sql = "SELECT * from (SELECT null as a, e1 FROM pm1.g1) b"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        List projectedSymbols = c.getProjectedSymbols();
-        for(int i=0; i< projectedSymbols.size(); i++) {
-            ElementSymbol symbol = (ElementSymbol)projectedSymbols.get(i);
-            assertTrue(!symbol.getType().equals(DataTypeManager.DefaultDataClasses.NULL));           
-        }
-    }
-    
-    @Test public void testDefect18832_2() {
-        String sql = "SELECT a.*, b.* from (SELECT null as a, e1 FROM pm1.g1) a, (SELECT e1 FROM pm1.g1) b"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        List projectedSymbols = c.getProjectedSymbols();
-        for(int i=0; i< projectedSymbols.size(); i++) {
-            ElementSymbol symbol = (ElementSymbol)projectedSymbols.get(i);
-            assertTrue(!symbol.getType().equals(DataTypeManager.DefaultDataClasses.NULL));           
-        }
-    }
-    
-    @Test public void testDefect20113() {
-        String sql = "SELECT g1.* from pm1.g1"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-
-    @Test public void testDefect20113_2() {
-        String sql = "SELECT g7.* from g7"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    private void verifyProjectedTypes(Command c, Class[] types) {
-        List projSymbols = c.getProjectedSymbols();
-        for(int i=0; i<projSymbols.size(); i++) {
-            assertEquals("Found type mismatch at column " + i, types[i], ((SingleElementSymbol) projSymbols.get(i)).getType()); //$NON-NLS-1$
-        }                
-    }
-    
-    @Test public void testNestedInlineViews() throws Exception {
-        String sql = "SELECT * FROM (SELECT * FROM (SELECT * FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        assertEquals(sql, c.toString());
-        
-        verifyProjectedTypes(c, new Class[] { String.class, Integer.class, Boolean.class, Double.class });
-    }
-
-    @Test public void testNestedInlineViewsNoStar() throws Exception {
-        String sql = "SELECT e1 FROM (SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        assertEquals(sql, c.toString());      
-        
-        verifyProjectedTypes(c, new Class[] { String.class });
-    }
-
-    @Test public void testNestedInlineViewsCount() throws Exception {
-        String sql = "SELECT COUNT(*) FROM (SELECT * FROM (SELECT * FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        assertEquals(sql, c.toString());        
-        verifyProjectedTypes(c, new Class[] { Integer.class });
-    }
-    
-    @Test public void testAggOverInlineView() throws Exception {
-        String sql = "SELECT SUM(x) FROM (SELECT (e2 + 1) AS x FROM pm1.g1) AS g"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        assertEquals(sql, c.toString());        
-        verifyProjectedTypes(c, new Class[] { Long.class });
-        
-    }
-
-    @Test public void testCaseOverInlineView() throws Exception {
-        String sql = "SELECT CASE WHEN x > 0 THEN 1.0 ELSE 2.0 END FROM (SELECT e2 AS x FROM pm1.g1) AS g"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        assertEquals(sql, c.toString());        
-        verifyProjectedTypes(c, new Class[] { Double.class });
-        
-    }
-    
-    //procedure - select * from temp table 
-    @Test public void testDefect20083_1 (){
-        helpResolve("EXEC pm1.vsp56()");   //$NON-NLS-1$
-    }
-    
-    //procedure - select * from temp table order by
-    @Test public void testDefect20083_2 (){
-        helpResolve("EXEC pm1.vsp57()");   //$NON-NLS-1$
-    }
-    
-    @Test public void testTypeConversionOverUnion() throws Exception { 
-        String sql = "SELECT * FROM (SELECT e2, e1 FROM pm1.g1 UNION SELECT convert(e2, string), e1 FROM pm1.g1) FOO where e2/2 = 1"; //$NON-NLS-1$ 
-        helpResolveException(sql); 
-    }
-    
-    @Test public void testVariableDeclarationAfterStatement() throws Exception{
-        String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "select * from pm1.g1 where pm1.g1.e1 = VARIABLES.X;\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE string VARIABLES.X = 1;\n";         //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        helpResolveException(procedure, "Element \"VARIABLES.X\" is not defined by any relevant group."); //$NON-NLS-1$
-    }
-    
-    /**
-     * same as above, but with an xml query 
-     * @throws Exception
-     */
-    @Test public void testVariableDeclarationAfterStatement1() throws Exception{
-        String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "select * from xmltest.doc1 where node1 = VARIABLES.X;\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE string VARIABLES.X = 1;\n";         //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        helpResolveException(procedure, "Error Code:ERR.015.008.0019 Message:Unable to resolve element: VARIABLES.X"); //$NON-NLS-1$
-    }
-    
-    @Test public void testCreate() {
-        String sql = "CREATE LOCAL TEMPORARY TABLE temp_table (column1 string)"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        assertEquals(sql, c.toString());  
-    }
-    
-    @Test public void testCreateQualifiedName() {
-        String sql = "CREATE LOCAL TEMPORARY TABLE pm1.g1 (column1 string)"; //$NON-NLS-1$
-        helpResolveException(sql, "Cannot create temporary table \"pm1.g1\". Local temporary tables must be created with unqualified names."); //$NON-NLS-1$
-    }
-
-    @Test public void testCreatePk() {
-        String sql = "CREATE LOCAL TEMPORARY TABLE foo (column1 string, column2 integer, primary key (column1, column2))"; //$NON-NLS-1$
-        helpResolve(sql);
-    }
-    
-    @Test public void testCreateUnknownPk() {
-        String sql = "CREATE LOCAL TEMPORARY TABLE foo (column1 string, primary key (column2))"; //$NON-NLS-1$
-        helpResolveException(sql, "Element \"column2\" is not defined by any relevant group."); //$NON-NLS-1$
-    }
-
-    @Test public void testCreateAlreadyExists() {
-        String sql = "CREATE LOCAL TEMPORARY TABLE g1 (column1 string)"; //$NON-NLS-1$
-        helpResolveException(sql, "Cannot create temporary table \"g1\". A table with the same name already exists."); //$NON-NLS-1$
-    }
-
-    @Test public void testCreateImplicitName() {
-        String sql = "CREATE LOCAL TEMPORARY TABLE #g1 (column1 string)"; //$NON-NLS-1$
-        Command c = helpResolve(sql);
-        assertEquals(sql, c.toString());
-    }
-    
-    @Test public void testCreateInProc() throws Exception{
-        helpResolveException("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table g1(c1 string); end", "Cannot create temporary table \"g1\". A table with the same name already exists.");//$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    //this was the old virt.agg procedure.  It was defined in such a way that relied on the scope leak of #temp
-    //the exception here is a little weak since there are multiple uses of #temp in the block
-    @Test public void testTempTableScope() {
-        String proc =  "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
-            + "BEGIN " //$NON-NLS-1$
-            + "        DECLARE integer VARIABLES.BITS;" //$NON-NLS-1$
-            + "        LOOP ON (SELECT DISTINCT phys.t.ID, phys.t.Name FROM phys.t) AS idCursor" //$NON-NLS-1$
-            + "        BEGIN" //$NON-NLS-1$
-            + "                VARIABLES.BITS = 0;" //$NON-NLS-1$
-            + "                LOOP ON (SELECT phys.t.source_bits FROM phys.t WHERE phys.t.ID = idCursor.id) AS bitsCursor" //$NON-NLS-1$
-            + "                BEGIN" //$NON-NLS-1$
-            + "                        VARIABLES.BITS = bitor(VARIABLES.BITS, bitsCursor.source_bits);" //$NON-NLS-1$
-            + "                END" //$NON-NLS-1$
-            + "                SELECT idCursor.id, idCursor.name, VARIABLES.BITS INTO #temp;" //$NON-NLS-1$
-            + "        END" //$NON-NLS-1$
-            + "        SELECT ID, Name, #temp.BITS AS source_bits FROM #temp;" //$NON-NLS-1$                                          
-            + "END"; //$NON-NLS-1$ 
-        
-        helpResolveException(proc, FakeMetadataFactory.exampleBitwise(), "Group does not exist: #temp"); //$NON-NLS-1$
-    }
-    
-    @Test public void testDrop() {
-        String sql = "DROP TABLE temp_table"; //$NON-NLS-1$
-        helpResolveException(sql, "Group does not exist: temp_table"); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testResolveUnqualifiedCriteria() throws Exception{
-        Criteria criteria = QueryParser.getQueryParser().parseCriteria("e1 = 1"); //$NON-NLS-1$
-           
-        // resolve
-        try { 
-            QueryResolver.resolveCriteria(criteria, metadata);
-            fail("Exception expected"); //$NON-NLS-1$
-        } catch(QueryResolverException e) {
-            assertEquals("Symbol e1 is specified with an unknown group context", e.getMessage()); //$NON-NLS-1$
-        } 
-    }
-    
-    @Test public void testSameNameRoot() {
-        String sql = "select p.e1 from pm1.g1 as pp, pm1.g1 as p"; //$NON-NLS-1$
-        
-        helpResolve(sql);
-    }
-    
-    @Test public void testDefect23342() throws Exception {
-        String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
-            + "BEGIN " //$NON-NLS-1$
-            + "IF (param = '1')" //$NON-NLS-1$
-            + " BEGIN " //$NON-NLS-1$
-            +"SELECT * FROM pm1.g1 where model.table.param=e1; " //$NON-NLS-1$
-            +" END " //$NON-NLS-1$
-            +"end "; //$NON-NLS-1$
-        Command command = helpParse(sql);
-        Map externalMetadata = new HashMap();
-        GroupSymbol proc = new GroupSymbol("model.table"); //$NON-NLS-1$
-        List procPrarms = new ArrayList();
-        ElementSymbol param = new ElementSymbol("model.table.param"); //$NON-NLS-1$
-        param.setType(DataTypeManager.DefaultDataClasses.STRING);
-        procPrarms.add(param);
-        externalMetadata.put(proc, procPrarms);
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-    }
-        
-    @Test public void testBatchedUpdateResolver() throws Exception {
-        String update1 = "update pm1.g1 set e1 =1"; //$NON-NLS-1$
-        String update2 = "update pm2.g1 set e1 =1"; //$NON-NLS-1$
-        
-        List commands = new ArrayList();
-        commands.add(QueryParser.getQueryParser().parseCommand(update1));
-        commands.add(QueryParser.getQueryParser().parseCommand(update2));
-        BatchedUpdateCommand command = new BatchedUpdateCommand(commands);
-        
-        helpResolve(command);
-    }
-    
-    @Test public void testAmbiguousAllInGroup() {
-        String sql = "SELECT g1.* from pm1.g1, pm2.g1"; //$NON-NLS-1$
-        helpResolveException(sql, metadata, "The symbol g1.* refers to more than one group defined in the FROM clause."); //$NON-NLS-1$
-    }
-    
-    @Test public void testRowsUpdatedInProcedure(){
-        String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
-            + "BEGIN " //$NON-NLS-1$
-            +"SELECT ROWS_UPDATED; " //$NON-NLS-1$
-            +"end "; //$NON-NLS-1$
-        
-        helpResolveException(sql, metadata, "Element \"ROWS_UPDATED\" is not defined by any relevant group."); //$NON-NLS-1$
-    }
-    
-    @Test public void testXMLQueryWithVariable() {
-        String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
-            + "BEGIN " //$NON-NLS-1$
-            + "declare string x = '1'; " //$NON-NLS-1$
-            +"select * from xmltest.doc1 where node1 = x; " //$NON-NLS-1$
-            +"end "; //$NON-NLS-1$
-
-        CreateUpdateProcedureCommand command = (CreateUpdateProcedureCommand) helpResolve(sql); 
-        
-        CommandStatement cmdStmt = (CommandStatement)command.getBlock().getStatements().get(1);
-        
-        CompareCriteria criteria = (CompareCriteria)((Query)cmdStmt.getCommand()).getCriteria();
-        
-        assertEquals(ProcedureReservedWords.VARIABLES, ((ElementSymbol)criteria.getRightExpression()).getGroupSymbol().getCanonicalName());
-    }
-    
-    /**
-     *  We could check to see if the expressions are evaluatable to a constant, but that seems unnecessary
-     */
-    @Test public void testLookupWithoutConstant() throws Exception{
-        String sql = "SELECT lookup('pm1.g1', convert('e3', float), 'e2', e2) FROM pm1.g1"; //$NON-NLS-1$
-        
-        helpResolveException(sql, metadata, "Error Code:ERR.015.008.0063 Message:The first three arguments for the LOOKUP function must be specified as constants."); //$NON-NLS-1$
-    }
-    
-    /**
-     * We cannot implicitly convert the argument to double due to lack of precision
-     */
-    @Test public void testPowerWithBigInteger_Fails() throws Exception {
-        String sql = "SELECT power(10, 999999999999999999999999999999999999999999999)"; //$NON-NLS-1$
-        
-        helpResolveException(sql);
-    }
-    
-    @Test public void testPowerWithLong_Fails() throws Exception {
-        String sql = "SELECT power(10, 999999999999)"; //$NON-NLS-1$
-        
-        helpResolveException(sql);
-    }
-    
-    @Test public void testUpdateError() {
-        String userUpdateStr = "UPDATE vm1.g2 SET e1='x'"; //$NON-NLS-1$
-        
-        helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Update is not allowed on the view vm1.g2: a procedure must be defined to handle the Update."); //$NON-NLS-1$
-    }
-    
-    @Test public void testInsertError() {
-        String userUpdateStr = "INSERT into vm1.g2 (e1) values ('x')"; //$NON-NLS-1$
-        
-        helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Insert is not allowed on the view vm1.g2: a procedure must be defined to handle the Insert."); //$NON-NLS-1$
-    }
-    
-    @Test public void testDeleteError() {
-        String userUpdateStr = "DELETE from vm1.g2 where e1='x'"; //$NON-NLS-1$
-        
-        helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Delete is not allowed on the view vm1.g2: a procedure must be defined to handle the Delete."); //$NON-NLS-1$
-    }
-                
-    @Test public void testResolveXMLSelect() {
-        String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE string VARIABLES.X = 1;\n";         //$NON-NLS-1$
-        procedure = procedure + "select VARIABLES.X from xmltest.doc1;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n";         //$NON-NLS-1$
-
-        helpResolveException(procedure, "Error Code:ERR.015.008.0019 Message:Unable to resolve element: VARIABLES.X"); //$NON-NLS-1$
-    }
-    
-    @Test public void testXMLJoinFail() {
-        String query = "select * from xmltest.doc1, xmltest.doc2"; //$NON-NLS-1$
-         
-        helpResolveException(query, "Error Code:ERR.015.008.0003 Message:Only one XML document may be specified in the FROM clause of a query."); //$NON-NLS-1$
-    }
-    
-    @Test public void testExecProjectedSymbols() {
-        String query = "exec pm1.sq1()"; //$NON-NLS-1$
-         
-        StoredProcedure proc = (StoredProcedure)helpResolve(query); 
-        
-        List projected = proc.getProjectedSymbols();
-        
-        assertEquals(2, projected.size());
-        
-        for (Iterator i = projected.iterator(); i.hasNext();) {
-            ElementSymbol symbol = (ElementSymbol)i.next();
-            assertNotNull(symbol.getGroupSymbol());
-        }
-    }
-    
-    @Test public void testExecWithDuplicateNames() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        
-        FakeMetadataStore store = metadata.getStore();
-        
-        FakeMetadataObject pm1 = store.findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "in", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("pm1.sq2", "CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq2.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        store.addObject(rs2);
-        store.addObject(sq2);
-        
-        helpResolveException("select * from pm1.sq2", metadata, "Cannot access procedure pm1.sq2 using table semantics since the parameter and result set column names are not all unique."); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInlineViewNullLiteralInUnion() {
-        String sql = "select e2 from pm1.g1 union all (select x from (select null as x) y)"; //$NON-NLS-1$
-        
-        helpResolve(sql);
-    }
-    
-    @Test public void testSelectIntoWithDuplicateNames() {
-        String sql = "select 1 as x, 2 as x into #temp"; //$NON-NLS-1$
-        
-        helpResolveException(sql, "Cannot create group '#temp' with multiple columns named 'x'"); //$NON-NLS-1$
-    }
-    
-    @Test public void testCreateWithDuplicateNames() {
-        String sql = "CREATE LOCAL TEMPORARY TABLE temp_table (column1 string, column1 string)"; //$NON-NLS-1$
-        
-        helpResolveException(sql, "Cannot create group \'temp_table\' with multiple columns named \'column1\'"); //$NON-NLS-1$
-    }
-    
-    @Test public void testXMLQuery4() {
-        helpResolveException("SELECT * FROM xmltest.doc1 group by a2", "Queries against XML documents can not have a GROUP By clause"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testXMLQuery5() {
-        helpResolveException("SELECT * FROM xmltest.doc1 having a2='x'", "Queries against XML documents can not have a HAVING clause"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testSelectIntoWithOrderBy() {
-        String sql = "select e1, e2 into #temp from pm1.g1 order by e1 limit 10"; //$NON-NLS-1$
-        
-        helpResolve(sql);
-    }
-    
-    @Test public void testUnionBranchesWithDifferentElementCounts() {
-        helpResolveException("SELECT e2, e3 FROM pm1.g1 UNION SELECT e2 FROM pm1.g2","Queries combined with the set operator UNION must have the same number of output elements."); //$NON-NLS-1$ //$NON-NLS-2$
-        helpResolveException("SELECT e2 FROM pm1.g1 UNION SELECT e2, e3 FROM pm1.g2","Queries combined with the set operator UNION must have the same number of output elements."); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testSelectIntoWithNullLiteral() {
-        String sql = "select null as x into #temp from pm1.g1"; //$NON-NLS-1$
-        
-        Query query = (Query)helpResolve(sql);
-        
-        TempMetadataStore store = new TempMetadataStore(query.getTemporaryMetadata());
-        
-        TempMetadataID id = store.getTempElementID("#temp.x"); //$NON-NLS-1$
-        
-        assertEquals(DataTypeManager.DefaultDataClasses.STRING, id.getType());
-    }
-    
-    @Test public void testInsertWithNullLiteral() {
-        String sql = "insert into #temp (x) values (null)"; //$NON-NLS-1$
-        
-        Insert insert = (Insert)helpResolve(sql);
-        
-        TempMetadataStore store = new TempMetadataStore(insert.getTemporaryMetadata());
-        
-        TempMetadataID id = store.getTempElementID("#temp.x"); //$NON-NLS-1$
-        
-        assertEquals(DataTypeManager.DefaultDataClasses.STRING, id.getType());
-    }
-    
-    @Test public void testInsertWithoutColumnsFails() {
-        String sql = "Insert into pm1.g1 values (1, 2)"; //$NON-NLS-1$
-        
-        helpResolveException(sql, "Error Code:ERR.015.008.0010 Message:INSERT statement must have the same number of elements and values specified.  This statement has 4 elements and 2 values."); //$NON-NLS-1$
-    }
-    
-    @Test public void testInsertWithoutColumnsFails1() {
-        String sql = "Insert into pm1.g1 values (1, 2, 3, 4)"; //$NON-NLS-1$
-        
-        helpResolveException(sql, "Error Code:ERR.015.008.0041 Message:Expected value of type 'boolean' but '3' is of type 'integer' and no implicit conversion is available."); //$NON-NLS-1$
-    }
-    
-    @Test public void testInsertWithQueryFails() {
-        String sql = "Insert into pm1.g1 select 1, 2, 3, 4"; //$NON-NLS-1$
-        
-        helpResolveException(sql, "Cannot convert insert query expression projected symbol '3' of type java.lang.Integer to insert column 'pm1.g1.e3' of type java.lang.Boolean"); //$NON-NLS-1$
-    }
-    
-    @Test public void testInsertWithQueryImplicitWithoutColumns() {
-        String sql = "Insert into #X select 1 as x, 2 as y, 3 as z"; //$NON-NLS-1$
-        helpResolve(sql); //$NON-NLS-1$
-    }
-    
-    @Test public void testInsertWithQueryImplicitWithoutColumns1() {
-        String sql = "Insert into #X select 1 as x, 2 as y, 3 as y"; //$NON-NLS-1$
-        
-        helpResolveException(sql, "Cannot create group '#X' with multiple columns named 'y'"); //$NON-NLS-1$
-    }
-
-    @Test public void testInsertWithoutColumnsPasses() {
-        String sql = "Insert into pm1.g1 values (1, 2, true, 4)"; //$NON-NLS-1$
-        
-        helpResolve(sql);
-        Insert command = (Insert)helpResolve(sql);
-        assertEquals(4, command.getVariables().size());
-    }
-
-    @Test public void testInsertWithoutColumnsUndefinedTemp() {
-        String sql = "Insert into #temp values (1, 2)"; //$NON-NLS-1$
-
-        Insert command = (Insert)helpResolve(sql);
-        assertEquals(2, command.getVariables().size());
-    }
-    
-    @Test public void testImplicitTempInsertWithNoColumns() {
-        StringBuffer proc = new StringBuffer("CREATE VIRTUAL PROCEDURE") //$NON-NLS-1$
-        .append("\nBEGIN") //$NON-NLS-1$
-        .append("\n  create local temporary table #matt (x integer);") //$NON-NLS-1$
-        .append("\n  insert into #matt values (1);") //$NON-NLS-1$
-        .append("\nEND"); //$NON-NLS-1$
-        
-        Command cmd = helpResolve(proc.toString()); 
-
-        String sExpected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nCREATE LOCAL TEMPORARY TABLE #matt (x integer);\nINSERT INTO #matt (#MATT.x) VALUES (1);\nEND\n\tCREATE LOCAL TEMPORARY TABLE #matt (x integer)\n\tINSERT INTO #matt (#MATT.x) VALUES (1)\n";   //$NON-NLS-1$
-        String sActual = cmd.printCommandTree(); 
-        assertEquals( sExpected, sActual );
-    }
-
-    @Test public void testCase6319() throws QueryResolverException, TeiidComponentException {
-        String sql = "select floatnum from bqt1.smalla group by floatnum having sum(floatnum) between 51.0 and 100.0 "; //$NON-NLS-1$
-        Query query = (Query)helpParse(sql);
-        QueryResolver.resolveCommand(query, FakeMetadataFactory.exampleBQTCached());
-    }
-
-    @Test public void testUniqeNamesWithInlineView() {
-        helpResolveException("select * from (select count(intNum) a, count(stringKey) b, bqt1.smalla.intkey as b from bqt1.smalla group by bqt1.smalla.intkey) q1 order by q1.a", FakeMetadataFactory.exampleBQTCached(), "Cannot create group 'q1' with multiple columns named 'b'"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-            
-    @Test public void testResolveOldProcRelational() {
-        helpResolveException("SELECT * FROM pm1.g1, (exec pm1.sq2(pm1.g1.e1)) as a", "Symbol pm1.g1.e1 is specified with an unknown group context"); //$NON-NLS-1$  //$NON-NLS-2$
-    }
-    
-    @Test public void testResolverOrderOfPrecedence() {
-        helpResolveException("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 CROSS JOIN (pm1.g2 LEFT OUTER JOIN pm2.g1 on pm1.g1.e1 = pm2.g1.e1)", "Symbol pm1.g1.e1 is specified with an unknown group context"); //$NON-NLS-1$  //$NON-NLS-2$
-    }
-    
-    /**
-     * The cross join should parse/resolve with higher precedence
-     */
-    @Test public void testResolverOrderOfPrecedence_1() {
-        helpResolve("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 CROSS JOIN pm1.g2 LEFT OUTER JOIN pm2.g1 on pm1.g1.e1 = pm2.g1.e1"); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvalidColumnReferenceWithNestedJoin() {
-    	helpResolveException("SELECT a.* FROM (pm1.g2 a left outer join pm1.g2 b on a.e1= b.e1) LEFT OUTER JOIN (select a.e1) c on (a.e1 = c.e1)"); //$NON-NLS-1$ 
-    }
-    
-    /**
-     * should be the same as exec with too many params
-     */
-	@Test public void testCallableStatementTooManyParameters() throws Exception {
-		String sql = "{call pm4.spTest9(?, ?)}"; //$NON-NLS-1$
-		
-		TestResolver.helpResolveException(sql, FakeMetadataFactory.exampleBQTCached(), "Error Code:ERR.015.008.0007 Message:Incorrect number of parameters specified on the stored procedure pm4.spTest9 - expected 1 but got 2"); //$NON-NLS-1$
-	}	
-	    
-    @Test public void testUpdateSetClauseReferenceType() {
-    	String sql = "UPDATE pm1.g1 SET pm1.g1.e1 = 1, pm1.g1.e2 = ?;"; //$NON-NLS-1$
-    	
-    	Update update = (Update)helpResolve(sql, FakeMetadataFactory.example1Cached(), null);
-    	
-    	Expression ref = update.getChangeList().getClauses().get(1).getValue();
-    	assertTrue(ref instanceof Reference);
-    	assertNotNull(ref.getType());
-    }
-    
-    @Test public void testNoTypeCriteria() {
-    	String sql = "select * from pm1.g1 where ? = ?"; //$NON-NLS-1$
-    	
-    	helpResolveException(sql, FakeMetadataFactory.example1Cached(), "Error Code:ERR.015.008.0026 Message:Expression '? = ?' has a parameter with non-determinable type information.  The use of an explicit convert may be necessary."); //$NON-NLS-1$
-    }
-    
-    @Test public void testReferenceInSelect() {
-    	String sql = "select ?, e1 from pm1.g1"; //$NON-NLS-1$
-    	Query command = (Query)helpResolve(sql, FakeMetadataFactory.example1Cached(), null);
-    	assertEquals(DataTypeManager.DefaultDataClasses.STRING, ((SingleElementSymbol)command.getProjectedSymbols().get(0)).getType());
-    }
-    
-    @Test public void testReferenceInSelect1() {
-    	String sql = "select convert(?, integer), e1 from pm1.g1"; //$NON-NLS-1$
-    	
-    	Query command = (Query)helpResolve(sql, FakeMetadataFactory.example1Cached(), null);
-    	assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(0)).getType());
-    }
-    
-    @Test public void testUnionWithObjectTypeConversion() {
-    	String sql = "select convert(null, xml) from pm1.g1 union all select 1"; //$NON-NLS-1$
-    	
-    	SetQuery query = (SetQuery)helpResolve(sql, FakeMetadataFactory.example1Cached(), null);
-    	assertEquals(DataTypeManager.DefaultDataClasses.OBJECT, ((SingleElementSymbol)query.getProjectedSymbols().get(0)).getType());
-    }
-    
-    @Test public void testUnionWithSubQuery() {
-    	String sql = "select 1 from pm1.g1 where exists (select 1) union select 2"; //$NON-NLS-1$
-
-        SetQuery command = (SetQuery)helpResolve(sql);
-        
-        assertEquals(1, command.getSubCommands().size());
-    }
-    @Test public void testOrderBy_J658a() {
-        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY e3"); //$NON-NLS-1$
-        OrderBy orderBy = resolvedQuery.getOrderBy();
-        int[] expectedPositions = new int[] {2};
-        helpTestOrderBy(orderBy, expectedPositions);
-    }
-
-	private void helpTestOrderBy(OrderBy orderBy, int[] expectedPositions) {
-		assertEquals(expectedPositions.length, orderBy.getVariableCount());
-        for (int i = 0; i < expectedPositions.length; i++) {
-        	assertEquals(expectedPositions[i], orderBy.getExpressionPosition(i));
-        }
-	}
-    @Test public void testOrderBy_J658b() {
-        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY e2, e3 "); //$NON-NLS-1$
-        helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
-    }
-    @Test public void testOrderBy_J658c() {
-        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY x, e3 "); //$NON-NLS-1$
-        helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});    
-    }
-    
-    // ambiguous, should fail
-    @Test public void testOrderBy_J658d() {
-        helpResolveException("SELECT pm1.g1.e1, e2 as x, e3 as x FROM pm1.g1 ORDER BY x, e1 ", "Error Code:ERR.015.008.0042 Message:Element 'x' in ORDER BY is ambiguous and may refer to more than one element of SELECT clause."); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    @Test public void testOrderBy_J658e() {
-        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as e2 FROM pm1.g1 ORDER BY x, e2 "); //$NON-NLS-1$
-        helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
-    }
-    
-    @Test public void testSPOutParamWithExec() {
-    	StoredProcedure proc = (StoredProcedure)helpResolve("exec pm2.spTest8(1)", FakeMetadataFactory.exampleBQTCached(), null);
-    	assertEquals(2, proc.getProjectedSymbols().size());
-    }
-
-    /**
-     * Note that the call syntax is not quite correct, the output parameter is not in the arg list.
-     * That hack is handled by the PreparedStatementRequest
-     */
-    @Test public void testSPOutParamWithCallableStatement() {
-    	StoredProcedure proc = (StoredProcedure)helpResolve("{call pm2.spTest8(1)}", FakeMetadataFactory.exampleBQTCached(), null);
-    	assertEquals(3, proc.getProjectedSymbols().size());
-    }
-    
-    @Test public void testOutWithWrongType() {
-    	helpResolveException("exec pm2.spTest8(inkey=>1, outkey=>{t '12:00:00'})", FakeMetadataFactory.exampleBQTCached());
-    }
-    
-    @Test public void testProcRelationalWithOutParam() {
-    	Query proc = (Query)helpResolve("select * from pm2.spTest8 where inkey = 1", FakeMetadataFactory.exampleBQTCached(), null);
-    	assertEquals(3, proc.getProjectedSymbols().size());
-    }
-    
-    @Test public void testSPReturnParamWithNoResultSet() {
-    	StoredProcedure proc = (StoredProcedure)helpResolve("exec pm4.spTest9(1)", FakeMetadataFactory.exampleBQTCached(), null);
-    	assertEquals(1, proc.getProjectedSymbols().size());
-    }
-    
-    @Test public void testSecondPassFunctionResolving() {
-    	helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where lower(?) = e1 "); //$NON-NLS-1$
-    }
-    
-    @Test public void testSecondPassFunctionResolving1() {
-    	try {
-    		helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where 1/(e1 - 2) <> 4 "); //$NON-NLS-1$
-    		fail("expected exception");
-    	} catch (RuntimeException e) {
-    		QueryResolverException qre = (QueryResolverException)e.getCause();
-    		assertEquals("ERR.015.008.0040", qre.getCode());
-    	}
-    }
-    
-    @Ignore("currently not supported - we get type hints from the criteria not from the possible signatures")
-    @Test public void testSecondPassFunctionResolving2() {
-    	helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where (lower(?) || 1) = e1 "); //$NON-NLS-1$
-    }
-
-    /**
-     * Test <code>QueryResolver</code>'s ability to resolve a query that 
-     * contains an aggregate <code>SUM</code> which uses a <code>CASE</code> 
-     * expression which contains <code>BETWEEN</code> criteria as its value.
-     * <p>
-     * For example:
-     * <p>
-     * SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1
-     */
-    @Test public void testAggregateWithBetweenInCaseInSelect() {
-    	String sql = "SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
-    	helpResolve(sql);
-    }
-    
-    /**
-     * Test <code>QueryResolver</code>'s ability to resolve a query that 
-     * contains a <code>CASE</code> expression which contains 
-     * <code>BETWEEN</code> criteria in the queries <code>SELECT</code> clause.
-     * <p>
-     * For example:
-     * <p>
-     * SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1
-     */
-    @Test public void testBetweenInCaseInSelect() {
-    	String sql = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
-    	helpResolve(sql);
-    }
-    
-    /**
-     * Test <code>QueryResolver</code>'s ability to resolve a query that 
-     * contains a <code>CASE</code> expression which contains 
-     * <code>BETWEEN</code> criteria in the queries <code>WHERE</code> clause.
-     * <p>
-     * For example:
-     * <p>
-     * SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END
-     */
-    @Test public void testBetweenInCase() {
-    	String sql = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END"; //$NON-NLS-1$
-    	helpResolve(sql);
-    }
-    
-    @Test public void testOrderByUnrelated() {
-        helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY e4"); //$NON-NLS-1$
-    }
-
-    @Test public void testOrderByUnrelated1() {
-        helpResolveException("SELECT distinct pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY e4"); //$NON-NLS-1$
-    }
-
-    @Test public void testOrderByUnrelated2() {
-        helpResolveException("SELECT max(e2) FROM pm1.g1 group by e1 ORDER BY e4"); //$NON-NLS-1$
-    }
-    
-    @Test public void testOrderByExpression() {
-    	Query query = (Query)helpResolve("select pm1.g1.e1 from pm1.g1 order by e2 || e3 "); //$NON-NLS-1$
-    	assertEquals(-1, query.getOrderBy().getExpressionPosition(0));
-    }
-    
-    @Test public void testOrderByExpression1() {
-    	Query query = (Query)helpResolve("select pm1.g1.e1 || e2 from pm1.g1 order by pm1.g1.e1 || e2 "); //$NON-NLS-1$
-    	assertEquals(0, query.getOrderBy().getExpressionPosition(0));
-    }
-    
-    @Test public void testOrderByExpression2() {
-    	helpResolveException("select pm1.g1.e1 from pm1.g1 union select pm1.g2.e1 from pm1.g2 order by pm1.g1.e1 || 2", "ORDER BY expression '(pm1.g1.e1 || 2)' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testOrderByConstantFails() {
-    	helpResolveException("select pm1.g1.e1 from pm1.g1 order by 2"); //$NON-NLS-1$
-    }
-    
-    @Test public void testCorrelatedNestedTableReference() {
-    	helpResolve("select pm1.g1.e1 from pm1.g1, table (exec pm1.sq2(pm1.g1.e2)) x"); //$NON-NLS-1$
-    	helpResolveException("select pm1.g1.e1 from pm1.g1, (exec pm1.sq2(pm1.g1.e2)) x"); //$NON-NLS-1$
-    }
-    
-    @Test public void testCorrelatedTextTable() {
-    	Command command = helpResolve("select x.* from pm1.g1, texttable(e1 COLUMNS x string) x"); //$NON-NLS-1$
-    	assertEquals(1, command.getProjectedSymbols().size());
-    }
-    
-    @Test public void testQueryString() throws Exception {
-    	helpResolveException("select querystring(xmlparse(document '<a/>'))");
-    }
-    
-	// validating AssignmentStatement, ROWS_UPDATED element assigned
-    @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure9() 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 + "ROWS_UPDATED = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
-        procedure = procedure + "ROWS_UPDATED =0;\n";         //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-        
-        helpResolveUpdateProcedure(procedure, userUpdateStr);
-    }
-
-	CreateUpdateProcedureCommand helpResolveUpdateProcedure(String procedure,
-			String userUpdateStr) throws QueryParserException,
-			QueryResolverException, TeiidComponentException,
-			QueryMetadataException {
-		FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
-        ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
-        QueryResolver.resolveCommand(userCommand, metadata);
-        
-        return (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, AnalysisRecord.createNonRecordingRecord());
-	}
-    
-	// validating AssignmentStatement, variable type and assigned type 
-	// do not match
-    @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure10() 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 + "var1 = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
-        procedure = procedure + "ROWS_UPDATED =0;\n";         //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-        
-		helpResolveUpdateProcedure(procedure, userUpdateStr);
-    }
-    
-    //return should be first, then out
-    @Test public void testParamOrder() {
-        Query resolvedQuery = (Query)helpResolve("SELECT * FROM (exec pm4.spRetOut()) as a", RealMetadataFactory.exampleBQTCached(), null); //$NON-NLS-1$
-        
-        assertEquals("A.ret", resolvedQuery.getProjectedSymbols().get(0).getName());
-    }
-    
-    @Test public void testWithDuplidateName() {
-    	helpResolveException("with x as (TABLE pm1.g1), x as (TABLE pm1.g2) SELECT * from x");
-    }
-    
-    @Test public void testWithColumns() {
-    	helpResolveException("with x (a, b) as (TABLE pm1.g1) SELECT * from x");
-    }
-    
-    @Test public void testWithNameMatchesFrom() {
-    	helpResolve("with x as (TABLE pm1.g1) SELECT * from (TABLE x) x");
-    }
-    
-	// variables cannot be used among insert elements
-    @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure23() 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 + "Update pm1.g1 SET pm1.g1.e2 =1 , var1 = 2;\n"; //$NON-NLS-1$
-        procedure = procedure + "ROWS_UPDATED =0;\n";         //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
-
-        helpResolveUpdateProcedure(procedure, userQuery);
-	}
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/query/resolver/TestResolver.java (from rev 2802, trunk/engine/src/test/java/org/teiid/query/resolver/TestResolver.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/query/resolver/TestResolver.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/engine/src/test/java/org/teiid/query/resolver/TestResolver.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,3102 @@
+/*
+ * 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.resolver;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+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.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryParserException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.function.FunctionTree;
+import org.teiid.query.function.UDFSource;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.optimizer.FakeFunctionMetadataSource;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.util.BindVariableVisitor;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.ProcedureReservedWords;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.OrderBy;
+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.Select;
+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.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.navigator.DeepPreOrderNavigator;
+import org.teiid.query.sql.proc.CommandStatement;
+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.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.SelectSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
+import org.teiid.query.unittest.FakeMetadataFacade;
+import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.unittest.TimestampUtil;
+
+ at SuppressWarnings("nls")
+public class TestResolver {
+
+	private FakeMetadataFacade metadata;
+
+	@Before public void setUp() {
+		metadata = FakeMetadataFactory.example1Cached();
+	}
+
+	// ################################## TEST HELPERS ################################
+
+	static Command helpParse(String sql) { 
+        try { 
+            return QueryParser.getQueryParser().parseCommand(sql);
+        } catch(TeiidException e) { 
+            throw new RuntimeException(e);
+        }
+	}
+    	
+    /**
+     * Helps resolve command, then check that the actual resolved Elements variables are the same as
+     * the expected variable names.  The variableNames param will be empty unless the subquery
+     * is a correlated subquery.
+     * @param sql Command to parse and resolve
+     * @param variableNames expected element symbol variable names, in order
+     * @return parsed and resolved Query
+     */
+    private Command helpResolveSubquery(String sql, String[] variableNames){
+        Query query = (Query)helpResolve(sql);
+        Collection<ElementSymbol> variables = getVariables(query);
+
+        assertTrue("Expected variables size " + variableNames.length + " but was " + variables.size(),  //$NON-NLS-1$ //$NON-NLS-2$
+                   variables.size() == variableNames.length);
+        Iterator variablesIter = variables.iterator();
+        for (int i=0; variablesIter.hasNext(); i++) {
+            ElementSymbol variable = (ElementSymbol)variablesIter.next();
+            assertTrue("Expected variable name " + variableNames[i] + " but was " + variable.getName(),  //$NON-NLS-1$ //$NON-NLS-2$
+                       variable.getName().equalsIgnoreCase(variableNames[i]));
+        }
+
+        if (variableNames.length == 0){
+            //There should be no TempMetadataIDs
+            Collection symbols = CheckNoTempMetadataIDsVisitor.checkSymbols(query);
+            assertTrue("Expected no symbols with temp metadataIDs, but got " + symbols, symbols.isEmpty()); //$NON-NLS-1$
+        }
+        
+        return query;         
+    }
+
+	public static Collection<ElementSymbol> getVariables(LanguageObject languageObject) {
+		Collection<ElementSymbol> variables = ElementCollectorVisitor.getElements(languageObject, false, true);
+    	for (Iterator<ElementSymbol> iterator = variables.iterator(); iterator.hasNext();) {
+			ElementSymbol elementSymbol = iterator.next();
+			if (!elementSymbol.isExternalReference()) {
+				iterator.remove();
+			}
+		}
+		return variables;
+	}
+    
+    public static Command helpResolve(String sql, QueryMetadataInterface queryMetadata, AnalysisRecord analysis){
+        return helpResolve(helpParse(sql), queryMetadata, analysis);
+    }
+    
+	private Command helpResolve(String sql) { 
+		return helpResolve(helpParse(sql));
+	}
+	
+    private Command helpResolve(Command command) {    
+        return helpResolve(command, this.metadata, AnalysisRecord.createNonRecordingRecord());  
+    }	
+
+	static Command helpResolve(Command command, QueryMetadataInterface queryMetadataInterface, AnalysisRecord analysis) {		
+        // resolve
+        try { 
+            QueryResolver.resolveCommand(command, queryMetadataInterface, analysis);
+        } catch(TeiidException e) {
+            throw new RuntimeException(e);
+        } 
+
+        CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
+        DeepPreOrderNavigator.doVisit(command, vis);
+        Collection unresolvedSymbols = vis.getUnresolvedSymbols();
+        assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
+        return command; 
+	}		
+
+	/**
+	 * Expect a QueryResolverException (not any other kind of Throwable)
+	 */
+	private void helpResolveFails(Command command) {
+		// resolve
+		QueryResolverException exception = null;
+		try {
+			QueryResolver.resolveCommand(command, metadata);
+		} catch(QueryResolverException e) {
+			exception = e;
+		} catch(TeiidException e) {
+			fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+		assertNotNull("Expected a QueryResolverException but got none.", exception); //$NON-NLS-1$
+	}
+
+    private Criteria helpResolveCriteria(String sql) { 
+        Criteria criteria = null;
+        
+        // parse
+        try { 
+            criteria = QueryParser.getQueryParser().parseCriteria(sql);
+           
+        } catch(TeiidException e) { 
+            fail("Exception during parsing (" + e.getClass().getName() + "): " + e.getMessage());    //$NON-NLS-1$ //$NON-NLS-2$
+        }   
+   
+   		// resolve
+        try { 
+            QueryResolver.resolveCriteria(criteria, metadata);
+        } catch(TeiidException e) {
+            e.printStackTrace();
+            fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } 
+
+        CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
+        DeepPreOrderNavigator.doVisit(criteria, vis);
+        Collection unresolvedSymbols = vis.getUnresolvedSymbols();
+        assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
+        return criteria;
+    }
+    
+    private Command helpResolve(String sql, List bindings) { 
+       
+        // parse
+        Command command = helpParse(sql);
+        
+        // apply bindings
+        if(bindings != null) {
+            try { 
+                BindVariableVisitor.bindReferences(command, bindings, metadata);
+            } catch(TeiidException e) { 
+                fail("Exception during binding (" + e.getClass().getName() + "): " + e.getMessage());    //$NON-NLS-1$ //$NON-NLS-2$
+            }   
+        }
+        
+        // resolve
+        try { 
+            QueryResolver.resolveCommand(command, metadata);
+        } catch(TeiidException e) { 
+            fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } 
+
+        CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
+        DeepPreOrderNavigator.doVisit(command, vis);
+
+        Collection unresolvedSymbols = vis.getUnresolvedSymbols();
+        assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
+        return command;
+    }
+
+    static void helpResolveException(String sql, QueryMetadataInterface queryMetadata){
+    	helpResolveException(sql, queryMetadata, null);	
+    }
+    
+    static void helpResolveException(String sql, QueryMetadataInterface queryMetadata, String expectedExceptionMessage){
+
+    	// parse
+        Command command = helpParse(sql);
+        
+        // resolve
+        try { 
+            QueryResolver.resolveCommand(command, queryMetadata);
+            fail("Expected exception for resolving " + sql);         //$NON-NLS-1$
+        } catch(QueryResolverException e) {
+        	if(expectedExceptionMessage != null){
+            	assertEquals(expectedExceptionMessage, e.getMessage());
+            }
+        } catch(TeiidComponentException e) {
+            throw new RuntimeException(e);
+        }       
+    }
+    
+	private void helpResolveException(String sql, String expectedExceptionMessage) {
+		TestResolver.helpResolveException(sql, this.metadata, expectedExceptionMessage);
+	}
+	
+	private void helpResolveException(String sql) {
+        TestResolver.helpResolveException(sql, this.metadata);
+	}
+	
+	private void helpCheckFrom(Query query, String[] groupIDs) { 
+		From from = query.getFrom();
+		List groups = from.getGroups();			
+		assertEquals("Wrong number of group IDs: ", groupIDs.length, groups.size()); //$NON-NLS-1$
+		
+		for(int i=0; i<groups.size(); i++) { 
+			GroupSymbol group = (GroupSymbol) groups.get(i);
+            String matchString = null;
+            if(group.getMetadataID() instanceof FakeMetadataObject) {
+                matchString = ((FakeMetadataObject)group.getMetadataID()).getName();
+            } else if(group.getMetadataID() instanceof TempMetadataID) {
+                matchString = ((TempMetadataID)group.getMetadataID()).getID();
+            }
+			assertEquals("Group ID does not match: ", groupIDs[i].toUpperCase(), matchString.toUpperCase()); //$NON-NLS-1$
+		}
+	}
+	
+	private void helpCheckSelect(Query query, String[] elementNames) {
+		Select select = query.getSelect();
+		List elements = select.getSymbols();
+		assertEquals("Wrong number of select symbols: ", elementNames.length, elements.size()); //$NON-NLS-1$
+
+		for(int i=0; i<elements.size(); i++) {
+			SelectSymbol symbol = (SelectSymbol) elements.get(i);
+			assertEquals("Element name does not match: ", elementNames[i].toUpperCase(), symbol.getName().toUpperCase()); //$NON-NLS-1$
+		}
+	}
+
+	private void helpCheckElements(LanguageObject langObj, String[] elementNames, String[] elementIDs) {
+		List elements = new ArrayList();
+		ElementCollectorVisitor.getElements(langObj, elements);
+		assertEquals("Wrong number of elements: ", elementNames.length, elements.size()); //$NON-NLS-1$
+
+		for(int i=0; i<elements.size(); i++) { 
+			ElementSymbol symbol = (ElementSymbol) elements.get(i);
+			assertEquals("Element name does not match: ", elementNames[i].toUpperCase(), symbol.getName().toUpperCase()); //$NON-NLS-1$
+			
+			FakeMetadataObject elementID = (FakeMetadataObject) symbol.getMetadataID();
+			assertNotNull("ElementSymbol " + symbol + " was not resolved and has no metadataID", elementID); //$NON-NLS-1$ //$NON-NLS-2$
+			assertEquals("ElementID name does not match: ", elementIDs[i].toUpperCase(), elementID.getName().toUpperCase()); //$NON-NLS-1$
+		}
+	}
+    
+    private void helpTestIsXMLQuery(String sql, boolean isXML) throws QueryResolverException, QueryMetadataException, TeiidComponentException {
+        // parse
+        Query query = (Query) helpParse(sql);
+
+        // check whether it's xml
+        boolean actual = QueryResolver.isXMLQuery(query, metadata);
+        assertEquals("Wrong answer for isXMLQuery", isXML, actual); //$NON-NLS-1$
+    }
+	
+    /**
+     * Helper method to resolve an exec aka stored procedure, then check that the
+     * expected parameter expressions are the same as actual parameter expressions. 
+     * @param sql
+     * @param expectedParameterExpressions
+     * @since 4.3
+     */
+    private StoredProcedure helpResolveExec(String sql, Object[] expectedParameterExpressions) {
+
+        StoredProcedure proc = (StoredProcedure)helpResolve(sql);
+        
+        List params = proc.getParameters();
+
+        // Remove all but IN and IN/OUT params
+        Iterator paramIter = params.iterator();
+        while (paramIter.hasNext()) {
+            final SPParameter param = (SPParameter)paramIter.next();
+            if (param.getParameterType() != ParameterInfo.IN && param.getParameterType() != ParameterInfo.INOUT) {
+                paramIter.remove();
+            }
+        }
+
+        // Check remaining params against expected expressions
+        assertEquals(expectedParameterExpressions.length, params.size());
+        for (int i=0; i<expectedParameterExpressions.length; i++) {
+            SPParameter param = (SPParameter)params.get(i);
+            if (expectedParameterExpressions[i] == null) {
+                assertNull(param.getExpression());
+            } else {
+                assertEquals(expectedParameterExpressions[i], param.getExpression());
+            }
+        }
+        
+        return proc;
+    }
+        
+    
+	// ################################## ACTUAL TESTS ################################
+	
+	
+	@Test public void testElementSymbolForms() {
+        String sql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 AS a, e4 AS b FROM pm1.g1"; //$NON-NLS-1$
+		Query resolvedQuery = (Query) helpResolve(sql);
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e2", "a", "b" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+		helpCheckElements(resolvedQuery.getSelect(), 
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
+	}
+
+	@Test public void testElementSymbolFormsWithAliasedGroup() {
+        String sql = "SELECT x.e1, e2, x.e3 AS a, e4 AS b FROM pm1.g1 AS x"; //$NON-NLS-1$
+		Query resolvedQuery = (Query) helpResolve(sql);
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "x.e1", "x.e2", "a", "b" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+		helpCheckElements(resolvedQuery.getSelect(),
+			new String[] { "x.e1", "x.e2", "x.e3", "x.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
+	}
+
+    @Test public void testGroupWithVDB() {
+        String sql = "SELECT e1 FROM myvdb.pm1.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
+    }
+
+    @Test public void testAliasedGroupWithVDB() {
+        String sql = "SELECT e1 FROM myvdb.pm1.g1 AS x"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString());         //$NON-NLS-1$
+    }
+    
+    @Test public void testPartiallyQualifiedGroup1() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT e1 FROM cat2.cat3.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1" }); //$NON-NLS-1$
+    }    
+    
+    @Test public void testPartiallyQualifiedGroup2() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT e1 FROM cat1.g2"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.g2" }); //$NON-NLS-1$
+    }
+    
+    @Test public void testPartiallyQualifiedGroup3() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT e1 FROM cat1.cat2.cat3.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1" }); //$NON-NLS-1$
+    }
+    
+    @Test public void testPartiallyQualifiedGroup4() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT e1 FROM cat2.g2"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm2.cat2.g2" }); //$NON-NLS-1$
+    }
+    
+    @Test public void testPartiallyQualifiedGroup5() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT e1 FROM cat2.g3"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat2.g3" }); //$NON-NLS-1$
+    }    
+    
+    @Test public void testPartiallyQualifiedGroup6() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT e1 FROM cat1.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm2.cat1.g1" }); //$NON-NLS-1$
+    }    
+    
+    @Test public void testPartiallyQualifiedGroup7() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT e1 FROM g4"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm2.g4" }); //$NON-NLS-1$
+    }    
+    
+    @Test public void testPartiallyQualifiedGroup8() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT e1 FROM pm2.g3"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm2.g3" }); //$NON-NLS-1$
+    }
+    
+    @Test public void testPartiallyQualifiedGroupWithAlias() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT X.e1 FROM cat2.cat3.g1 as X"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1" }); //$NON-NLS-1$
+    } 
+    
+    @Test public void testPartiallyQualifiedElement1() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT cat2.cat3.g1.e1 FROM cat2.cat3.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1" }); //$NON-NLS-1$
+    }
+
+    /** defect 12536 */
+    @Test public void testPartiallyQualifiedElement2() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT cat3.g1.e1 FROM cat2.cat3.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1" }); //$NON-NLS-1$
+    }
+    
+    /** defect 12536 */
+    @Test public void testPartiallyQualifiedElement3() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT cat3.g1.e1 FROM cat2.cat3.g1, cat1.g2"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1" }); //$NON-NLS-1$
+    }
+    
+    /** defect 12536 */
+    @Test public void testPartiallyQualifiedElement4() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT cat3.g1.e1, cat1.g2.e1 FROM cat2.cat3.g1, cat1.g2"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.g2.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+    
+    @Test public void testPartiallyQualifiedElement5() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT cat3.g1.e1, cat1.g2.e1 FROM myvdb.pm1.cat1.cat2.cat3.g1, pm1.cat1.g2"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.g2.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+    
+    /** defect 12536 */
+    @Test public void testPartiallyQualifiedElement6() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT cat3.g1.e1, e2 FROM cat2.cat3.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+	    helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.cat2.cat3.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+    
+    @Test public void testPartiallyQualifiedElement7() {
+    	metadata = FakeMetadataFactory.example3();
+        String sql = "SELECT cat3.g1.e1, cat2.cat3.g1.e2, g1.e3 FROM pm1.cat1.cat2.cat3.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.cat2.cat3.g1.e2", "pm1.cat1.cat2.cat3.g1.e3" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    } 
+    
+    @Test public void testFailPartiallyQualifiedGroup1() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT e1 FROM cat3.g1"); //$NON-NLS-1$
+    }
+    
+    @Test public void testFailPartiallyQualifiedGroup2() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT e1 FROM g1"); //$NON-NLS-1$
+    }
+    
+    @Test public void testFailPartiallyQualifiedGroup3() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT e1 FROM g2"); //$NON-NLS-1$
+    }
+    
+    @Test public void testFailPartiallyQualifiedGroup4() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT e1 FROM g3"); //$NON-NLS-1$
+    }
+    
+    @Test public void testFailPartiallyQualifiedGroup5() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT e1 FROM g5");		 //$NON-NLS-1$
+    }
+    
+    @Test public void testFailPartiallyQualifiedElement1() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT cat3.g1.e1 FROM pm1.cat1.cat2.cat3.g1, pm2.cat3.g1"); //$NON-NLS-1$
+    }
+    
+    @Test public void testFailPartiallyQualifiedElement2() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT g1.e1 FROM pm1.cat1.cat2.cat3.g1, pm2.cat3.g1"); //$NON-NLS-1$
+    }
+    
+    @Test public void testFailPartiallyQualifiedElement3() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2, pm1.cat2.g3"); //$NON-NLS-1$
+    }
+    
+    @Test public void testFailPartiallyQualifiedElement4() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2"); //$NON-NLS-1$
+    }
+    
+    @Test public void testFailPartiallyQualifiedElement5() {
+    	metadata = FakeMetadataFactory.example3();
+		helpResolveException("SELECT cat3.g1.e1 FROM g1"); //$NON-NLS-1$
+    }    
+
+    @Test public void testElementWithVDB() {
+        String sql = "SELECT myvdb.pm1.g1.e1 FROM pm1.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+        helpCheckElements(resolvedQuery.getSelect(),
+            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
+    }
+
+    @Test public void testAliasedElementWithVDB() {
+        Query resolvedQuery = (Query) helpResolve("SELECT myvdb.pm1.g1.e1 AS x FROM pm1.g1"); //$NON-NLS-1$
+        helpCheckSelect(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
+        helpCheckElements(resolvedQuery.getSelect(),
+            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+    }
+
+	@Test public void testSelectStar() {
+		Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g1"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
+		helpCheckElements(resolvedQuery.getSelect(),
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}
+
+	@Test public void testSelectStarFromAliasedGroup() {
+		Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g1 as x"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
+		helpCheckElements(resolvedQuery.getSelect(),
+			new String[] { "x.e1", "x.e2", "x.e3", "x.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}
+
+	@Test public void testSelectStarFromMultipleAliasedGroups() {
+		Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g1 as x, pm1.g1 as y"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1", "pm1.g1" }); //$NON-NLS-1$ //$NON-NLS-2$
+		helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
+		helpCheckElements(resolvedQuery.getSelect(),
+			new String[] { "x.e1", "x.e2", "x.e3", "x.e4", "y.e1", "y.e2", "y.e3", "y.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4", "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+	}
+
+    @Test public void testSelectStarWhereSomeElementsAreNotSelectable() {
+        Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g4"); //$NON-NLS-1$
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.g4" }); //$NON-NLS-1$
+        helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
+        helpCheckElements(resolvedQuery.getSelect(),
+            new String[] { "pm1.g4.e1", "pm1.g4.e3" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { "pm1.g4.e1", "pm1.g4.e3" } ); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testSelectGroupStarWhereSomeElementsAreNotSelectable() {
+        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g4.* FROM pm1.g4"); //$NON-NLS-1$
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.g4" }); //$NON-NLS-1$
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.g4.*" }); //$NON-NLS-1$
+        helpCheckElements(resolvedQuery.getSelect(),
+            new String[] { "pm1.g4.e1", "pm1.g4.e3" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { "pm1.g4.e1", "pm1.g4.e3" } ); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+	@Test public void testFullyQualifiedSelectStar() {
+		Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.* FROM pm1.g1"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.*" }); //$NON-NLS-1$
+		helpCheckElements(resolvedQuery.getSelect(),
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}
+
+	@Test public void testSelectAllInAliasedGroup() {
+		Query resolvedQuery = (Query) helpResolve("SELECT x.* FROM pm1.g1 as x"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "x.*" }); //$NON-NLS-1$
+		helpCheckElements(resolvedQuery.getSelect(),
+			new String[] { "x.e1", "x.e2", "x.e3", "x.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}
+
+	@Test public void testSelectExpressions() {
+		Query resolvedQuery = (Query) helpResolve("SELECT e1, concat(e1, 's'), concat(e1, 's') as c FROM pm1.g1"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "expr", "c" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		helpCheckElements(resolvedQuery.getSelect(),
+			new String[] { "pm1.g1.e1", "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			new String[] { "pm1.g1.e1", "pm1.g1.e1", "pm1.g1.e1" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+
+	@Test public void testSelectCountStar() {
+		Query resolvedQuery = (Query) helpResolve("SELECT count(*) FROM pm1.g1"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "count" }); //$NON-NLS-1$
+		helpCheckElements(resolvedQuery.getSelect(), new String[] { }, new String[] { } );
+	}
+	
+	@Test public void testMultipleIdenticalElements() { 
+		Query resolvedQuery = (Query) helpResolve("SELECT e1, e1 FROM pm1.g1"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+		helpCheckElements(resolvedQuery.getSelect(), 
+			new String[] { "pm1.g1.e1", "pm1.g1.e1" },  //$NON-NLS-1$ //$NON-NLS-2$
+			new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	@Test public void testMultipleIdenticalElements2() { 
+		Query resolvedQuery = (Query) helpResolve("SELECT e1, pm1.g1.e1 FROM pm1.g1"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+		helpCheckElements(resolvedQuery.getSelect(), 
+			new String[] { "pm1.g1.e1", "pm1.g1.e1" },  //$NON-NLS-1$ //$NON-NLS-2$
+			new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	@Test public void testMultipleIdenticalElements3() { 
+		Query resolvedQuery = (Query) helpResolve("SELECT e1, e1 as x FROM pm1.g1"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
+		helpCheckElements(resolvedQuery.getSelect(), 
+			new String[] { "pm1.g1.e1", "pm1.g1.e1" },  //$NON-NLS-1$ //$NON-NLS-2$
+			new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+	@Test public void testDifferentElementsSameName() { 
+		Query resolvedQuery = (Query) helpResolve("SELECT e1 as x, e2 as x FROM pm1.g2"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g2" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "x", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
+		helpCheckElements(resolvedQuery.getSelect(), 
+			new String[] { "pm1.g2.e1", "pm1.g2.e2" },  //$NON-NLS-1$ //$NON-NLS-2$
+			new String[] { "pm1.g2.e1", "pm1.g2.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	@Test public void testDifferentConstantsSameName() { 
+		Query resolvedQuery = (Query) helpResolve("SELECT 1 as x, 2 as x FROM pm1.g2"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g2" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "x", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
+		helpCheckElements(resolvedQuery.getSelect(), 
+			new String[] { }, 
+			new String[] { });
+	}
+	
+	@Test public void testFailSameGroupsWithSameNames() { 
+		helpResolveException("SELECT * FROM pm1.g1 as x, pm1.g1 as x"); //$NON-NLS-1$
+	}
+
+	@Test public void testFailDifferentGroupsWithSameNames() { 
+		helpResolveException("SELECT * FROM pm1.g1 as x, pm1.g2 as x"); //$NON-NLS-1$
+	}
+
+	@Test public void testFailAmbiguousElement() { 
+		helpResolveException("SELECT e1 FROM pm1.g1, pm1.g2"); //$NON-NLS-1$
+	}
+
+	@Test public void testFailAmbiguousElementAliasedGroup() { 
+		helpResolveException("SELECT e1 FROM pm1.g1 as x, pm1.g1"); //$NON-NLS-1$
+	}
+
+	@Test public void testFailFullyQualifiedElementUnknownGroup() { 
+		helpResolveException("SELECT pm1.g1.e1 FROM pm1.g2"); //$NON-NLS-1$
+	}
+
+	@Test public void testFailUnknownGroup() { 
+		helpResolveException("SELECT x.e1 FROM x"); //$NON-NLS-1$
+	}
+
+	@Test public void testFailUnknownElement() { 
+		helpResolveException("SELECT x FROM pm1.g1"); //$NON-NLS-1$
+	}
+
+    @Test public void testFailFunctionOfAggregatesInSelect() {        
+        helpResolveException("SELECT (SUM(e0) * COUNT(e0)) FROM test.group GROUP BY e0"); //$NON-NLS-1$
+    }
+	
+	/*
+	 * per defect 4404 
+	 */
+	@Test public void testFailGroupNotReferencedByAlias() { 
+		helpResolveException("SELECT pm1.g1.x FROM pm1.g1 as H"); //$NON-NLS-1$
+	}
+
+	/*
+	 * per defect 4404 - this one reproduced the defect,
+	 * then succeeded after the fix
+	 */
+	@Test public void testFailGroupNotReferencedByAliasSelectAll() { 
+		helpResolveException("SELECT pm1.g1.* FROM pm1.g1 as H"); //$NON-NLS-1$
+	}
+
+	@Test public void testComplicatedQuery() {
+		Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e2 as y, pm1.g1.E3 as z, CONVERT(pm1.g1.e1, integer) * 1000 as w  FROM pm1.g1 WHERE e1 <> 'x'"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckSelect(resolvedQuery, new String[] { "y", "z", "w" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		helpCheckElements(resolvedQuery, 
+			new String[] { "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e1" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}
+	
+	@Test public void testJoinQuery() {
+		Query resolvedQuery = (Query) helpResolve("SELECT pm3.g1.e2, pm3.g2.e2 FROM pm3.g1, pm3.g2 WHERE pm3.g1.e2=pm3.g2.e2"); //$NON-NLS-1$
+		helpCheckFrom(resolvedQuery, new String[] { "pm3.g1", "pm3.g2" }); //$NON-NLS-1$ //$NON-NLS-2$
+		helpCheckSelect(resolvedQuery, new String[] { "pm3.g1.e2", "pm3.g2.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
+		helpCheckElements(resolvedQuery, 
+			new String[] { "pm3.g1.e2", "pm3.g2.e2", "pm3.g1.e2", "pm3.g2.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { "pm3.g1.e2", "pm3.g2.e2", "pm3.g1.e2", "pm3.g2.e2" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}
+	
+    @Test public void testHavingRequiringConvertOnAggregate1() {
+        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MAX(e2) > 1.2"); //$NON-NLS-1$
+    }
+
+    @Test public void testHavingRequiringConvertOnAggregate2() {
+        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MIN(e2) > 1.2"); //$NON-NLS-1$
+    }
+
+    @Test public void testHavingRequiringConvertOnAggregate3() {
+        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING 1.2 > MAX(e2)"); //$NON-NLS-1$
+    }
+
+    @Test public void testHavingRequiringConvertOnAggregate4() {
+        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING 1.2 > MIN(e2)"); //$NON-NLS-1$
+    }
+
+    @Test public void testHavingWithAggsOfDifferentTypes() {
+        helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MIN(e1) = MIN(e2)"); //$NON-NLS-1$
+    }
+    
+    @Test public void testCaseInGroupBy() {
+        String sql = "SELECT SUM(e2) FROM pm1.g1 GROUP BY CASE WHEN e2 = 0 THEN 1 ELSE 2 END"; //$NON-NLS-1$
+        Command command = helpResolve(sql);
+        assertEquals(sql, command.toString());
+        
+        helpCheckElements(command, new String[] {"pm1.g1.e2", "pm1.g1.e2"}, new String[] {"pm1.g1.e2", "pm1.g1.e2"});  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
+    }
+
+    @Test public void testFunctionInGroupBy() {
+        String sql = "SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)"; //$NON-NLS-1$
+        Command command = helpResolve(sql);
+        assertEquals(sql, command.toString());
+        
+        helpCheckElements(command, new String[] {"pm1.g1.e2", "pm1.g1.e2"}, new String[] {"pm1.g1.e2", "pm1.g1.e2"});  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
+    }
+
+	@Test public void testUnknownFunction() {	    
+		helpResolveException("SELECT abc(e1) FROM pm1.g1", "Error Code:ERR.015.008.0039 Message:The function 'abc(e1)' is an unknown form.  Check that the function name and number of arguments is correct."); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	@Test public void testConversionNotPossible() {	    
+		helpResolveException("SELECT dayofmonth('2002-01-01') FROM pm1.g1", "Error Code:ERR.015.008.0040 Message:The function 'dayofmonth('2002-01-01')' is a valid function form, but the arguments do not match a known type signature and cannot be converted using implicit type conversions."); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+    
+    @Test public void testResolveParameters() {
+        List bindings = new ArrayList();
+        bindings.add("pm1.g2.e1"); //$NON-NLS-1$
+        bindings.add("pm1.g2.e2"); //$NON-NLS-1$
+        
+        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, ? FROM pm1.g1 WHERE pm1.g1.e1 = ?", bindings); //$NON-NLS-1$
+
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "expr" }); //$NON-NLS-1$ //$NON-NLS-2$
+        helpCheckElements(resolvedQuery.getCriteria(), 
+            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+            
+    }
+
+    @Test public void testResolveParametersInsert() {
+        List bindings = new ArrayList();
+        bindings.add("pm1.g2.e1"); //$NON-NLS-1$
+        
+        helpResolve("INSERT INTO pm1.g1 (e1) VALUES (?)", bindings); //$NON-NLS-1$
+    }
+    
+    @Test public void testResolveParametersExec() {
+        List bindings = new ArrayList();
+        bindings.add("pm1.g2.e1"); //$NON-NLS-1$
+        
+        Query resolvedQuery = (Query)helpResolve("SELECT * FROM (exec pm1.sq2(?)) as a", bindings); //$NON-NLS-1$
+        //verify the type of the reference is resolved
+        List refs = ReferenceCollectorVisitor.getReferences(resolvedQuery);
+        Reference ref = (Reference)refs.get(0);
+        assertNotNull(ref.getType());
+    }
+
+    @Test public void testUseNonExistentAlias() {
+        helpResolveException("SELECT portfoliob.e1 FROM ((pm1.g1 AS portfoliob JOIN pm1.g2 AS portidentb ON portfoliob.e1 = portidentb.e1) RIGHT OUTER JOIN pm1.g3 AS identifiersb ON portidentb.e1 = 'ISIN' and portidentb.e2 = identifiersb.e2) RIGHT OUTER JOIN pm1.g1 AS issuesb ON a.identifiersb.e1 = issuesb.e1"); //$NON-NLS-1$
+    }       
+
+    @Test public void testCriteria1() {                  
+        CompareCriteria expected = new CompareCriteria();
+        ElementSymbol es = new ElementSymbol("pm1.g1.e1"); //$NON-NLS-1$
+        GroupSymbol gs = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
+        es.setGroupSymbol(gs);
+        expected.setLeftExpression(es);
+        expected.setOperator(CompareCriteria.EQ);
+        expected.setRightExpression(new Constant("abc")); //$NON-NLS-1$
+
+        Criteria actual = helpResolveCriteria("pm1.g1.e1 = 'abc'"); //$NON-NLS-1$
+
+        assertEquals("Did not match expected criteria", expected, actual);         //$NON-NLS-1$
+    }
+        
+    @Test public void testSubquery1() {
+        Query resolvedQuery = (Query) helpResolve("SELECT e1 FROM pm1.g1, (SELECT pm1.g2.e1 AS x FROM pm1.g2) AS y WHERE e1 = x"); //$NON-NLS-1$
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1", "y" }); //$NON-NLS-1$ //$NON-NLS-2$
+        helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+        helpCheckElements(resolvedQuery.getSelect(),
+            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+        
+    }
+    
+    @Test public void testStoredQuery1() {                
+        StoredProcedure proc = (StoredProcedure) helpResolve("EXEC pm1.sq2('abc')"); //$NON-NLS-1$
+        
+        // Check number of resolved parameters
+        List params = proc.getParameters();
+        assertEquals("Did not get expected parameter count", 2, params.size()); //$NON-NLS-1$
+        
+        // Check resolved parameters
+        SPParameter param1 = (SPParameter) params.get(0);
+        helpCheckParameter(param1, ParameterInfo.RESULT_SET, 1, "pm1.sq2.ret", java.sql.ResultSet.class, null); //$NON-NLS-1$
+
+        SPParameter param2 = (SPParameter) params.get(1);
+        helpCheckParameter(param2, ParameterInfo.IN, 2, "pm1.sq2.in", DataTypeManager.DefaultDataClasses.STRING, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+	/**
+	 * per defect 8211 - Input params do not have to be numbered sequentially in metadata.  For example,
+	 * the first input param can be #1 and the second input param can be #3.  (This occurs in 
+	 * QueryBuilder's metadata where the return param happens to be created in between the two
+	 * input params and is numbered #2, but is not loaded into QueryBuilder's runtime env).  
+	 * When the user's query is parsed and resolved, the placeholder
+	 * input params are numbered #1 and #2.  This test tests that this disparity in ordering should not
+	 * be a problem as long as RELATIVE ordering is in synch.
+	 */
+	@Test public void testStoredQueryParamOrdering_8211() {                
+		StoredProcedure proc = (StoredProcedure) helpResolve("EXEC pm1.sq3a('abc', 123)"); //$NON-NLS-1$
+		
+		// Check number of resolved parameters
+		List params = proc.getParameters();
+		assertEquals("Did not get expected parameter count", 2, params.size()); //$NON-NLS-1$
+        
+		// Check resolved parameters
+		SPParameter param1 = (SPParameter) params.get(0);
+		helpCheckParameter(param1, ParameterInfo.IN, 1, "pm1.sq3a.in", DataTypeManager.DefaultDataClasses.STRING, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
+
+		SPParameter param2 = (SPParameter) params.get(1);
+		helpCheckParameter(param2, ParameterInfo.IN, 3, "pm1.sq3a.in2", DataTypeManager.DefaultDataClasses.INTEGER, new Constant(new Integer(123))); //$NON-NLS-1$
+	}    
+    
+    private void helpCheckParameter(SPParameter param, int paramType, int index, String name, Class type, Expression expr) {
+        assertEquals("Did not get expected parameter type", paramType, param.getParameterType()); //$NON-NLS-1$
+        assertEquals("Did not get expected index for param", index, param.getIndex()); //$NON-NLS-1$
+        assertEquals("Did not get expected name for param", name, param.getName()); //$NON-NLS-1$
+        assertEquals("Did not get expected type for param", type, param.getClassType()); //$NON-NLS-1$
+        assertEquals("Did not get expected type for param", expr, param.getExpression());                 //$NON-NLS-1$
+    }
+    
+    @Test public void testStoredSubQuery1() {
+        Query resolvedQuery = (Query) helpResolve("select x.e1 from (EXEC pm1.sq1()) as x"); //$NON-NLS-1$
+        helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
+        helpCheckSelect(resolvedQuery, new String[] { "x.e1" });         //$NON-NLS-1$
+    }
+    
+    @Test public void testStoredSubQuery2() {
+        Query resolvedQuery = (Query) helpResolve("select x.e1 from (EXEC pm1.sq3('abc', 5)) as x"); //$NON-NLS-1$
+        helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
+        helpCheckSelect(resolvedQuery, new String[] { "x.e1" });         //$NON-NLS-1$
+    }
+
+    @Test public void testStoredSubQuery3() {
+        Query resolvedQuery = (Query) helpResolve("select * from (EXEC pm1.sq2('abc')) as x"); //$NON-NLS-1$
+        helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
+        
+        List elements = (List) ElementCollectorVisitor.getElements(resolvedQuery.getSelect(), false);
+        
+        ElementSymbol elem1 = (ElementSymbol)elements.get(0);
+        assertEquals("Did not get expected element", "X.e1", elem1.getName() ); //$NON-NLS-1$ //$NON-NLS-2$
+        assertEquals("Did not get expected type", DataTypeManager.DefaultDataClasses.STRING, elem1.getType()); //$NON-NLS-1$
+
+        ElementSymbol elem2 = (ElementSymbol)elements.get(1);
+        assertEquals("Did not get expected element", "X.e2", elem2.getName() ); //$NON-NLS-1$ //$NON-NLS-2$
+        assertEquals("Did not get expected type", DataTypeManager.DefaultDataClasses.INTEGER, elem2.getType()); //$NON-NLS-1$
+    }
+
+    @Test public void testStoredQueryTransformationWithVariable() throws Exception {
+        Command command = QueryParser.getQueryParser().parseCommand("SELECT * FROM pm1.g1 WHERE pm1.sq5.in1 = 5"); //$NON-NLS-1$
+        
+        // Construct command metadata 
+        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5");  //$NON-NLS-1$
+        ArrayList sqParams = new ArrayList();
+        ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
+        in.setType(DataTypeManager.DefaultDataClasses.STRING);
+        sqParams.add(in);
+        Map externalMetadata = new HashMap();
+        externalMetadata.put(sqGroup, sqParams);
+        
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+
+        // Verify results        
+        helpCheckFrom((Query)command, new String[] { "pm1.g1" });         //$NON-NLS-1$
+        Collection vars = getVariables(command);
+        assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
+    }
+
+    @Test public void testStoredQueryTransformationWithVariable2() throws Exception {
+        Command command = QueryParser.getQueryParser().parseCommand("SELECT * FROM pm1.g1 WHERE in1 = 5"); //$NON-NLS-1$
+        
+        // Construct command metadata
+        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5");  //$NON-NLS-1$
+        ArrayList sqParams = new ArrayList();
+        ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
+        in.setType(DataTypeManager.DefaultDataClasses.STRING);
+        sqParams.add(in);
+        Map externalMetadata = new HashMap();
+        externalMetadata.put(sqGroup, sqParams);
+                    
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+
+        // Verify results        
+        helpCheckFrom((Query)command, new String[] { "pm1.g1" });         //$NON-NLS-1$
+        Collection vars = getVariables(command);
+        assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
+    }
+
+    @Test public void testStoredQueryTransformationWithVariable3() throws Exception {
+        Command command = QueryParser.getQueryParser().parseCommand("SELECT * FROM pm1.g1 WHERE in1 = 5 UNION SELECT * FROM pm1.g1"); //$NON-NLS-1$
+
+        // Construct command metadata
+        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
+        ArrayList sqParams = new ArrayList();
+        ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
+        in.setType(DataTypeManager.DefaultDataClasses.STRING);
+        sqParams.add(in);
+        Map externalMetadata = new HashMap();
+        externalMetadata.put(sqGroup, sqParams);
+
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+
+        // Verify results
+        Collection vars = getVariables(command);
+        assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
+    }
+    
+    @Test public void testStoredQueryTransformationWithVariable4() throws Exception {
+        Command command = QueryParser.getQueryParser().parseCommand("EXEC pm1.sq2(pm1.sq2.in)"); //$NON-NLS-1$
+
+        // resolve
+        try {
+            // Construct command metadata
+            GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
+            ArrayList sqParams = new ArrayList();
+            ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
+            in.setType(DataTypeManager.DefaultDataClasses.STRING);
+            sqParams.add(in);
+            Map externalMetadata = new HashMap();
+            externalMetadata.put(sqGroup, sqParams);
+
+            QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+            
+            fail("Expected exception on invalid variable pm1.sq2.in"); //$NON-NLS-1$
+        } catch(QueryResolverException e) {
+        	assertEquals("Symbol pm1.sq2.\"in\" is specified with an unknown group context", e.getMessage()); //$NON-NLS-1$
+        } 
+    }
+
+    @Test public void testExec1() {
+        helpResolve("EXEC pm1.sq2('xyz')"); //$NON-NLS-1$
+    }
+
+    @Test public void testExec2() {
+        // implicity convert 5 to proper type
+        helpResolve("EXEC pm1.sq2(5)"); //$NON-NLS-1$
+    }
+    
+    @Test public void testExecNamedParam() {
+        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz")};//$NON-NLS-1$
+        helpResolveExec("EXEC pm1.sq2(\"in\" = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
+    }
+    
+    @Test public void testExecNamedParamDup() {
+        helpResolveException("EXEC pm1.sq2(\"in\" = 'xyz', \"in\" = 'xyz1')");//$NON-NLS-1$
+    }
+
+    /** Should get exception because param name is wrong. */
+    @Test public void testExecWrongParamName() {
+        helpResolveException("EXEC pm1.sq2(in1 = 'xyz')");//$NON-NLS-1$
+    }
+
+    @Test public void testExecNamedParams() {
+        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(5))};//$NON-NLS-1$
+        helpResolveExec("EXEC pm1.sq3(\"in\" = 'xyz', in2 = 5)", expectedParameterExpressions);//$NON-NLS-1$
+    }   
+    
+    /** try entering params out of order */
+    @Test public void testExecNamedParamsReversed() {
+        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(5))};//$NON-NLS-1$
+        helpResolveExec("EXEC pm1.sq3(in2 = 5, \"in\" = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
+    }    
+    
+    /** test omitting an optional parameter */
+    @Test public void testExecNamedParamsOptionalParam() {
+        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(null), new Constant("something")};//$NON-NLS-1$ //$NON-NLS-2$
+        helpResolveExec("EXEC pm1.sq3b(\"in\" = 'xyz', in3 = 'something')", expectedParameterExpressions);//$NON-NLS-1$
+    }    
+
+    /** test omitting a required parameter that has a default value */
+    @Test public void testExecNamedParamsOmitRequiredParamWithDefaultValue() {
+        Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(666)), new Constant("YYZ")};//$NON-NLS-1$ //$NON-NLS-2$
+        StoredProcedure sp = helpResolveExec("EXEC pm1.sq3b(\"in\" = 'xyz', in2 = 666)", expectedParameterExpressions);//$NON-NLS-1$
+        assertEquals("EXEC pm1.sq3b(\"in\" => 'xyz', in2 => 666)", sp.toString());
+    }    
+    
+    @Test public void testExecNamedParamsOptionalParamWithDefaults() {
+        Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
+        //override the default value for the first parameter
+        expectedParameterExpressions[0] = new Constant("xyz"); //$NON-NLS-1$
+        helpResolveExec("EXEC pm1.sqDefaults(inString = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
+    }    
+
+    @Test public void testExecNamedParamsOptionalParamWithDefaultsCaseInsensitive() {
+        Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
+        //override the default value for the first parameter
+        expectedParameterExpressions[0] = new Constant("xyz"); //$NON-NLS-1$
+        helpResolveExec("EXEC pm1.sqDefaults(iNsTrInG = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
+    }    
+
+    /** try just a few named parameters, in no particular order */
+    @Test public void testExecNamedParamsOptionalParamWithDefaults2() {
+        Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
+        //override the proper default values in expected results
+        expectedParameterExpressions[3] = new Constant(Boolean.FALSE); 
+        expectedParameterExpressions[9] = new Constant(new Integer(666));
+        helpResolveExec("EXEC pm1.sqDefaults(ininteger = 666, inboolean={b'false'})", expectedParameterExpressions);//$NON-NLS-1$
+    }    
+
+    /** 
+     * Try entering in no actual parameters, rely entirely on defaults.  
+     * This also tests the default value transformation code in ExecResolver. 
+     */
+    @Test public void testExecNamedParamsOptionalParamWithAllDefaults() {
+        Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
+        helpResolveExec("EXEC pm1.sqDefaults()", expectedParameterExpressions);//$NON-NLS-1$
+    }     
+
+    /**
+     * Retrieve the Object array of expected default values for the stored procedure
+     * "pm1.sqDefaults" in FakeMetadataFactory.example1().
+     * @return
+     * @since 4.3
+     */
+    private Object[] helpGetStoredProcDefaultValues() {
+        
+        // This needs to match what's in FakeMetadataFactory.example1 for this stored proc
+        return new Object[]  {
+            new Constant("x"), //$NON-NLS-1$
+            new Constant(new BigDecimal("13.0")),//$NON-NLS-1$
+            new Constant(new BigInteger("13")),//$NON-NLS-1$
+            new Constant(Boolean.TRUE),
+            new Constant(new Byte("1")),//$NON-NLS-1$
+            new Constant(new Character('q')),
+            new Constant(Date.valueOf("2003-03-20")),//$NON-NLS-1$
+            new Constant(new Double(13.0)),
+            new Constant(new Float(13.0)),
+            new Constant(new Integer(13)),
+            new Constant(new Long(13)),
+            new Constant(new Short((short)13)),
+            new Constant(Timestamp.valueOf("2003-03-20 21:26:00.000000")),//$NON-NLS-1$
+            new Constant(Time.valueOf("21:26:00")),//$NON-NLS-1$
+        };
+    }
+    
+    /** Should get exception because there are two required params */
+    @Test public void testExceptionNotSupplyingRequiredParam() {
+        helpResolveException("EXEC pm1.sq3(in2 = 5)");//$NON-NLS-1$
+    }
+    
+    /** Should get exception because the default value in metadata is bad for input param */
+    @Test public void testExceptionBadDefaultValue() {
+        helpResolveException("EXEC pm1.sqBadDefault()");//$NON-NLS-1$
+    }
+    
+    @Test public void testExecWithForcedConvertOfStringToCorrectType() {
+        // force conversion of '5' to proper type (integer)
+        helpResolve("EXEC pm1.sq3('x', '5')"); //$NON-NLS-1$
+    }
+
+    /**
+     * True/false are consistently representable by integers
+     */
+    @Test public void testExecBadType() {
+        helpResolve("EXEC pm1.sq3('xyz', {b'true'})"); //$NON-NLS-1$
+    }
+    
+    @Test public void testSubqueryInUnion() {
+        String sql = "SELECT IntKey, FloatNum FROM BQT1.MediumA WHERE (IntKey >= 0) AND (IntKey < 15) " + //$NON-NLS-1$
+            "UNION ALL " + //$NON-NLS-1$
+            "SELECT BQT2.SmallB.IntKey, y.FloatNum " +  //$NON-NLS-1$
+            "FROM BQT2.SmallB INNER JOIN " + //$NON-NLS-1$
+            "(SELECT IntKey, FloatNum FROM BQT1.MediumA ) AS y ON BQT2.SmallB.IntKey = y.IntKey " + //$NON-NLS-1$
+            "WHERE (y.IntKey >= 10) AND (y.IntKey < 30) " + //$NON-NLS-1$
+            "ORDER BY IntKey, FloatNum";  //$NON-NLS-1$
+
+        helpResolve(sql, FakeMetadataFactory.exampleBQTCached(), null);
+    }
+
+    @Test public void testSubQueryINClause1(){
+		//select e1 from pm1.g1 where e2 in (select e2 from pm4.g1)
+
+		//sub command
+		Select innerSelect = new Select();
+		ElementSymbol e2inner = new ElementSymbol("e2"); //$NON-NLS-1$
+		innerSelect.addSymbol(e2inner);
+		From innerFrom = new From();
+		GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
+		innerFrom.addGroup(pm4g1);
+		Query innerQuery = new Query();
+		innerQuery.setSelect(innerSelect);
+		innerQuery.setFrom(innerFrom);
+		
+		//outer command
+		Select outerSelect = new Select();
+		ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+    	outerSelect.addSymbol(e1);
+		From outerFrom = new From();
+    	GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
+		outerFrom.addGroup(pm1g1);
+    	ElementSymbol e2outer = new ElementSymbol("e2"); //$NON-NLS-1$
+		SubquerySetCriteria crit = new SubquerySetCriteria(e2outer, innerQuery);
+    	Query outerQuery = new Query();
+    	outerQuery.setSelect(outerSelect);
+    	outerQuery.setFrom(outerFrom);
+    	outerQuery.setCriteria(crit);
+    	
+    	//test
+    	helpResolve(outerQuery);
+
+    	helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+    	helpCheckFrom(innerQuery, new String[] { "pm4.g1" }); //$NON-NLS-1$
+    	helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+    	helpCheckSelect(innerQuery, new String[] { "pm4.g1.e2" }); //$NON-NLS-1$
+    	helpCheckElements(outerQuery.getSelect(),
+    		new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+    		new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+    	helpCheckElements(innerQuery.getSelect(),
+    		new String[] { "pm4.g1.e2" }, //$NON-NLS-1$
+    		new String[] { "pm4.g1.e2" } ); //$NON-NLS-1$
+
+    	String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm4.g1)"; //$NON-NLS-1$
+    	assertEquals("Resolved string form was incorrect ", sql, outerQuery.toString()); //$NON-NLS-1$
+    }    
+
+	/**
+	 * An implicit type conversion needs to be inserted because the
+	 * project symbol of the subquery is not the same type as the expression in
+	 * the SubquerySetCriteria object
+	 */
+	@Test public void testSubQueryINClauseImplicitConversion(){
+		//select e1 from pm1.g1 where e2 in (select e1 from pm4.g1)
+	
+		//sub command
+		Select innerSelect = new Select();
+		ElementSymbol e1inner = new ElementSymbol("e1"); //$NON-NLS-1$
+		innerSelect.addSymbol(e1inner);
+		From innerFrom = new From();
+		GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
+		innerFrom.addGroup(pm4g1);
+		Query innerQuery = new Query();
+		innerQuery.setSelect(innerSelect);
+		innerQuery.setFrom(innerFrom);
+		
+		//outer command
+		Select outerSelect = new Select();
+		ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+		outerSelect.addSymbol(e1);
+		From outerFrom = new From();
+		GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
+		outerFrom.addGroup(pm1g1);
+		ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
+		SubquerySetCriteria crit = new SubquerySetCriteria(e2, innerQuery);
+		Query outerQuery = new Query();
+		outerQuery.setSelect(outerSelect);
+		outerQuery.setFrom(outerFrom);
+		outerQuery.setCriteria(crit);
+		
+		//test
+		helpResolve(outerQuery);
+		
+		helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+		helpCheckFrom(innerQuery, new String[] { "pm4.g1" }); //$NON-NLS-1$
+		helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+		helpCheckSelect(innerQuery, new String[] { "pm4.g1.e1" }); //$NON-NLS-1$
+		helpCheckElements(outerQuery.getSelect(),
+			new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+			new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+		helpCheckElements(innerQuery.getSelect(),
+			new String[] { "pm4.g1.e1" }, //$NON-NLS-1$
+			new String[] { "pm4.g1.e1" } ); //$NON-NLS-1$
+		
+		String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e1 FROM pm4.g1)"; //$NON-NLS-1$
+		assertEquals("Resolved string form was incorrect ", sql, outerQuery.toString()); //$NON-NLS-1$
+		
+		//make sure there is a convert function wrapping the criteria left expression
+		Collection functions = FunctionCollectorVisitor.getFunctions(outerQuery, true);
+		assertTrue(functions.size() == 1);
+		Function function = (Function)functions.iterator().next();
+		assertTrue(function.getName().equals(FunctionLibrary.CONVERT));
+		Expression[] args = function.getArgs();
+		assertSame(e2, args[0]);
+		assertTrue(args[1] instanceof Constant);		
+	}
+    
+	/**
+	 * Tests that resolving fails if there is no implicit conversion between the
+	 * type of the expression of the SubquerySetCriteria and the type of the
+	 * projected symbol of the subquery.
+	 */
+	@Test public void testSubQueryINClauseNoConversionFails(){
+		//select e1 from pm1.g1 where e1 in (select e2 from pm4.g1)
+
+		//sub command
+		Select innerSelect = new Select();
+		ElementSymbol e2inner = new ElementSymbol("e2"); //$NON-NLS-1$
+		innerSelect.addSymbol(e2inner);
+		From innerFrom = new From();
+		GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
+		innerFrom.addGroup(pm4g1);
+		Query innerQuery = new Query();
+		innerQuery.setSelect(innerSelect);
+		innerQuery.setFrom(innerFrom);
+
+		//outer command
+		Select outerSelect = new Select();
+		ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+		outerSelect.addSymbol(e1);
+		From outerFrom = new From();
+		GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
+		outerFrom.addGroup(pm1g1);
+		SubquerySetCriteria crit = new SubquerySetCriteria(e1, innerQuery);
+		Query outerQuery = new Query();
+		outerQuery.setSelect(outerSelect);
+		outerQuery.setFrom(outerFrom);
+		outerQuery.setCriteria(crit);
+
+		//test
+		this.helpResolveFails(outerQuery);
+	}
+
+    @Test public void testSubQueryINClauseTooManyColumns(){
+        String sql = "select e1 from pm1.g1 where e1 in (select e1, e2 from pm4.g1)"; //$NON-NLS-1$
+
+        //test
+        this.helpResolveException(sql);
+    }
+
+	@Test public void testStoredQueryInFROMSubquery() {
+		String sql = "select X.e1 from (EXEC pm1.sq3('abc', 123)) as X"; //$NON-NLS-1$
+
+        helpResolve(sql);
+	}
+	
+	@Test public void testStoredQueryInINSubquery() throws Exception {
+		String sql = "select * from pm1.g1 where e1 in (EXEC pm1.sqsp1())"; //$NON-NLS-1$
+
+        helpResolve(sql);
+	}	
+    
+    @Test public void testIsXMLQuery1() throws Exception {
+        helpTestIsXMLQuery("SELECT * FROM pm1.g1", false);     //$NON-NLS-1$
+    }
+
+    @Test public void testIsXMLQuery2() throws Exception {
+        helpTestIsXMLQuery("SELECT * FROM xmltest.doc1", true); //$NON-NLS-1$
+    }
+
+    /**
+     * Must be able to resolve XML query if short doc name
+     * is used (assuming short doc name isn't ambiguous in a
+     * VDB).  Defect 11479.
+     */
+    @Test public void testIsXMLQuery3() throws Exception {
+        helpTestIsXMLQuery("SELECT * FROM doc1", true); //$NON-NLS-1$
+    }
+
+    @Test public void testIsXMLQueryFail1() throws Exception {
+        helpTestIsXMLQuery("SELECT * FROM xmltest.doc1, xmltest.doc2", false); //$NON-NLS-1$
+    }
+
+    @Test public void testIsXMLQueryFail2() throws Exception {
+        helpTestIsXMLQuery("SELECT * FROM xmltest.doc1, pm1.g1", false); //$NON-NLS-1$
+    }
+
+    @Test public void testIsXMLQueryFail3() throws Exception {
+        helpTestIsXMLQuery("SELECT * FROM pm1.g1, xmltest.doc1", false); //$NON-NLS-1$
+    }
+
+    /**
+     * "docA" is ambiguous as there exist two documents called
+     * xmlTest2.docA and xmlTest3.docA.  Defect 11479.
+     */
+    @Test public void testIsXMLQueryFail4() throws Exception {
+        Query query = (Query) helpParse("SELECT * FROM docA"); //$NON-NLS-1$
+
+        try {
+            QueryResolver.isXMLQuery(query, metadata);
+            fail("expected exception"); //$NON-NLS-1$
+        } catch (QueryResolverException e) {
+            assertEquals("Group specified is ambiguous, resubmit the query by fully qualifying the group name: docA", e.getMessage()); //$NON-NLS-1$
+        }
+    }
+    
+    @Test public void testStringConversion1() {
+		// Expected left expression
+        ElementSymbol e1 = new ElementSymbol("pm3.g1.e2"); //$NON-NLS-1$
+        e1.setType(DataTypeManager.DefaultDataClasses.DATE);
+      
+        // Expected right expression
+        Class srcType = DataTypeManager.DefaultDataClasses.STRING;
+        String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
+        Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
+        
+		FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();                         
+		FunctionDescriptor fd = library.findFunction(FunctionLibrary.CONVERT, new Class[] { srcType, DataTypeManager.DefaultDataClasses.STRING });
+
+		Function conversion = new Function(fd.getName(), new Expression[] { expression, new Constant(tgtTypeName) });
+		conversion.setType(DataTypeManager.getDataTypeClass(tgtTypeName));
+		conversion.setFunctionDescriptor(fd);
+		conversion.makeImplicit();
+		
+		// Expected criteria
+		CompareCriteria expected = new CompareCriteria();
+		expected.setLeftExpression(e1);
+		expected.setOperator(CompareCriteria.EQ);
+		expected.setRightExpression(conversion);
+         
+		// Resolve the query and check against expected objects
+		CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e2='2003-02-27'");	 //$NON-NLS-1$
+	
+		//if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
+		//	fail("left exprs not equal");
+		//} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
+		//	fail("right not equal");
+		//}
+		
+		assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+    }
+		
+	@Test public void testStringConversion2() {
+		// Expected left expression
+		ElementSymbol e1 = new ElementSymbol("pm3.g1.e2"); //$NON-NLS-1$
+		e1.setType(DataTypeManager.DefaultDataClasses.DATE);
+      
+		// Expected right expression
+		Class srcType = DataTypeManager.DefaultDataClasses.STRING;
+		String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
+		Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
+        
+		FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();                        
+		FunctionDescriptor fd = library.findFunction(FunctionLibrary.CONVERT, new Class[] { srcType, DataTypeManager.DefaultDataClasses.STRING });
+
+		Function conversion = new Function(fd.getName(), new Expression[] { expression, new Constant(tgtTypeName) });
+		conversion.setType(DataTypeManager.getDataTypeClass(tgtTypeName));
+		conversion.setFunctionDescriptor(fd);
+		conversion.makeImplicit();
+		
+		// Expected criteria
+		CompareCriteria expected = new CompareCriteria();
+		expected.setLeftExpression(conversion);
+		expected.setOperator(CompareCriteria.EQ);
+		expected.setRightExpression(e1);
+         
+		// Resolve the query and check against expected objects
+		CompareCriteria actual = (CompareCriteria) helpResolveCriteria("'2003-02-27'=pm3.g1.e2");	 //$NON-NLS-1$
+	
+		//if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
+		//	fail("Left expressions not equal");
+		//} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
+		//	fail("Right expressions not equal");
+		//}
+		
+		assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+	}		
+    
+    // special test for both sides are String
+	@Test public void testStringConversion3() {
+		// Expected left expression
+		ElementSymbol e1 = new ElementSymbol("pm3.g1.e1"); //$NON-NLS-1$
+		e1.setType(DataTypeManager.DefaultDataClasses.STRING);
+			   
+		// Expected right expression
+		Constant e2 = new Constant("2003-02-27"); //$NON-NLS-1$
+			   
+		// Expected criteria
+		CompareCriteria expected = new CompareCriteria();
+		expected.setLeftExpression(e1);
+		expected.setOperator(CompareCriteria.EQ);
+		expected.setRightExpression(e2);
+         
+		// Resolve the query and check against expected objects
+		CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e1='2003-02-27'");	 //$NON-NLS-1$
+		
+		//if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
+		//	System.out.println("left exprs not equal");
+		//} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
+		//	System.out.println("right exprs not equal");
+		//}
+		
+		assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+	}	
+
+    @Test public void testDateToTimestampConversion_defect9747() {
+        // Expected left expression
+        ElementSymbol e1 = new ElementSymbol("pm3.g1.e4"); //$NON-NLS-1$
+        e1.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
+               
+        // Expected right expression
+        Constant e2 = new Constant(TimestampUtil.createDate(96, 0, 31), DataTypeManager.DefaultDataClasses.DATE);
+        Function f1 = new Function("convert", new Expression[] { e2, new Constant(DataTypeManager.DefaultDataTypes.TIMESTAMP)}); //$NON-NLS-1$
+        f1.makeImplicit();
+               
+        // Expected criteria
+        CompareCriteria expected = new CompareCriteria();
+        expected.setLeftExpression(e1);
+        expected.setOperator(CompareCriteria.GT);
+        expected.setRightExpression(f1);
+         
+        // Resolve the query and check against expected objects
+        CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e4 > {d '1996-01-31'}");    //$NON-NLS-1$
+        
+        assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+    }   
+        
+    @Test public void testFailedConversion_defect9725() throws Exception{
+    	helpResolveException("select * from pm3.g1 where pm3.g1.e4 > {b 'true'}", "Error Code:ERR.015.008.0027 Message:The expressions in this criteria are being compared but are of differing types (timestamp and boolean) and no implicit conversion is available:  pm3.g1.e4 > TRUE"); //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+            
+    @Test public void testLookupFunction() {     
+        String sql = "SELECT lookup('pm1.g1', 'e1', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve(sql);
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+        helpCheckSelect(resolvedQuery, new String[] { "x", "y" }); //$NON-NLS-1$ //$NON-NLS-2$
+        helpCheckElements(resolvedQuery.getSelect(), 
+            new String[] { "PM1.G1.E2", "PM1.G1.E3" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { "PM1.G1.E2", "PM1.G1.E3" } ); //$NON-NLS-1$ //$NON-NLS-2$
+        assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
+        
+        List projSymbols = resolvedQuery.getSelect().getProjectedSymbols();
+        assertEquals("Wrong number of projected symbols", 2, projSymbols.size()); //$NON-NLS-1$
+        assertEquals("Wrong type for first symbol", String.class, ((SingleElementSymbol)projSymbols.get(0)).getType()); //$NON-NLS-1$
+        assertEquals("Wrong type for second symbol", Double.class, ((SingleElementSymbol)projSymbols.get(1)).getType()); //$NON-NLS-1$
+    }
+
+    @Test public void testLookupFunctionFailBadElement() {     
+        String sql = "SELECT lookup('nosuch', 'elementhere', 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
+        helpResolveException(sql);
+    }
+
+    @Test public void testLookupFunctionFailNotConstantArg1() {     
+        String sql = "SELECT lookup(e1, 'e1', 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
+        helpResolveException(sql);
+    }
+
+    @Test public void testLookupFunctionFailNotConstantArg2() {     
+        String sql = "SELECT lookup('pm1.g1', e1, 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
+        helpResolveException(sql);
+    }
+   		
+    @Test public void testLookupFunctionFailNotConstantArg3() {     
+        String sql = "SELECT lookup('pm1.g1', 'e1', e1, e2) AS x FROM pm1.g1"; //$NON-NLS-1$
+        helpResolveException(sql);
+    }
+ 
+	@Test public void testLookupFunctionVirtualGroup() throws Exception {     
+		String sql = "SELECT lookup('vm1.g1', 'e1', 'e2', e2)  FROM vm1.g1 "; //$NON-NLS-1$
+		Query command = (Query) helpParse(sql);
+		QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());  		
+	}
+	
+	@Test public void testLookupFunctionPhysicalGroup() throws Exception {     
+		String sql = "SELECT lookup('pm1.g1', 'e1', 'e2', e2)  FROM pm1.g1 "; //$NON-NLS-1$
+		Query command = (Query) helpParse(sql);
+		QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
+	}
+	
+    @Test public void testLookupFunctionFailBadKeyElement() throws Exception {
+    	String sql = "SELECT lookup('pm1.g1', 'e1', 'x', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
+    	Command command = QueryParser.getQueryParser().parseCommand(sql);
+    	try {
+    		QueryResolver.resolveCommand(command, metadata);
+    		fail("exception expected"); //$NON-NLS-1$
+    	} catch (QueryResolverException e) {
+    		
+    	}
+    }
+    
+	@Test public void testNamespacedFunction() throws Exception {     
+		String sql = "SELECT namespace.func('e1')  FROM vm1.g1 "; //$NON-NLS-1$
+
+        FunctionLibrary funcLibrary = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree(new UDFSource(new FakeFunctionMetadataSource().getFunctionMethods())));
+        FakeMetadataFacade metadata = new FakeMetadataFacade(FakeMetadataFactory.example1Cached().getStore(), funcLibrary);
+		
+		Query command = (Query) helpParse(sql);
+		QueryResolver.resolveCommand(command, metadata);
+		
+		command = (Query) helpParse("SELECT func('e1')  FROM vm1.g1 ");
+		QueryResolver.resolveCommand(command, metadata);  		
+		
+	}    
+    
+    // special test for both sides are String
+    @Test public void testSetCriteriaCastFromExpression_9657() {
+        // parse
+        Criteria expected = null;
+        Criteria actual = null;
+        try { 
+            actual = QueryParser.getQueryParser().parseCriteria("bqt1.smalla.shortvalue IN (1, 2)"); //$NON-NLS-1$
+            expected = QueryParser.getQueryParser().parseCriteria("convert(bqt1.smalla.shortvalue, integer) IN (1, 2)"); //$NON-NLS-1$
+           
+        } catch(TeiidException e) { 
+            fail("Exception during parsing (" + e.getClass().getName() + "): " + e.getMessage());    //$NON-NLS-1$ //$NON-NLS-2$
+        }   
+   
+        // resolve
+        try { 
+            QueryResolver.resolveCriteria(expected, FakeMetadataFactory.exampleBQTCached());
+            QueryResolver.resolveCriteria(actual, FakeMetadataFactory.exampleBQTCached());
+        } catch(TeiidException e) { 
+            fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } 
+        
+        // Tweak expected to hide convert function - this is expected
+        ((Function) ((SetCriteria)expected).getExpression()).makeImplicit();
+        
+        assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+    }    
+    
+    /** select e1 from pm1.g1 where e2 BETWEEN 1000 AND 2000 */
+    @Test public void testBetween1(){
+        String sql = "select e1 from pm1.g1 where e2 BETWEEN 1000 AND 2000"; //$NON-NLS-1$
+        helpResolve(sql);
+    } 
+
+    /** select e1 from pm1.g1 where e2 NOT BETWEEN 1000 AND 2000 */
+    @Test public void testBetween2(){
+        String sql = "select e1 from pm1.g1 where e2 NOT BETWEEN 1000 AND 2000"; //$NON-NLS-1$
+        helpResolve(sql);
+    } 
+
+    /** select e2 from pm1.g1 where e4 BETWEEN 1000 AND e2 */
+    @Test public void testBetween3(){
+        String sql = "select e2 from pm1.g1 where e4 BETWEEN 1000 AND e2"; //$NON-NLS-1$
+        helpResolve(sql);
+    } 
+
+    /** select e2 from pm1.g1 where e2 BETWEEN 1000 AND e4 */
+    @Test public void testBetween4(){
+        String sql = "select e2 from pm1.g1 where e2 BETWEEN 1000 AND e4"; //$NON-NLS-1$
+        helpResolve(sql);
+    } 
+
+    /** select e1 from pm1.g1 where 1000 BETWEEN e1 AND e2 */
+    @Test public void testBetween5(){
+        String sql = "select e1 from pm1.g1 where 1000 BETWEEN e1 AND e2"; //$NON-NLS-1$
+        helpResolve(sql);
+    } 
+
+    /** select e1 from pm1.g1 where 1000 BETWEEN e2 AND e1 */
+    @Test public void testBetween6(){
+        String sql = "select e1 from pm1.g1 where 1000 BETWEEN e2 AND e1"; //$NON-NLS-1$
+        helpResolve(sql);
+    } 
+
+    /** select e1 from pm3.g1 where e2 BETWEEN e3 AND e4 */
+    @Test public void testBetween7(){
+        String sql = "select e1 from pm3.g1 where e2 BETWEEN e3 AND e4"; //$NON-NLS-1$
+        helpResolve(sql);
+    } 
+
+    /** select pm3.g1.e1 from pm3.g1, pm3.g2 where pm3.g1.e4 BETWEEN pm3.g1.e2 AND pm3.g2.e2 */
+    @Test public void testBetween8(){
+        String sql = "select pm3.g1.e1 from pm3.g1, pm3.g2 where pm3.g1.e4 BETWEEN pm3.g1.e2 AND pm3.g2.e2"; //$NON-NLS-1$
+        helpResolve(sql);
+    } 
+
+    /** select e1 from pm1.g1 where e2 = any (select e2 from pm4.g1) */
+    @Test public void testCompareSubQuery1(){
+
+        String sql = "select e1 from pm1.g1 where e2 = any (select e2 from pm4.g1)"; //$NON-NLS-1$
+        Query outerQuery = (Query) this.helpResolveSubquery(sql, new String[0]);
+
+        helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+        helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+        helpCheckElements(outerQuery.getSelect(),
+            new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+            new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+//        helpCheckFrom(innerQuery, new String[] { "pm4.g1" });
+//        helpCheckSelect(innerQuery, new String[] { "pm4.g1.e2" });
+//        helpCheckElements(innerQuery.getSelect(),
+//            new String[] { "pm4.g1.e2" },
+//            new String[] { "pm4.g1.e2" } );
+
+        String sqlActual = "SELECT e1 FROM pm1.g1 WHERE e2 = ANY (SELECT e2 FROM pm4.g1)"; //$NON-NLS-1$
+        assertEquals("Resolved string form was incorrect ", sqlActual, outerQuery.toString()); //$NON-NLS-1$
+    }    
+
+    /** select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1) */
+    @Test public void testCompareSubQuery2(){
+        String sql = "select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    } 
+
+    /** select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3') */
+    @Test public void testCompareSubQuery3(){
+        String sql = "select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3')"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    } 
+
+    /** select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3') */
+    @Test public void testCompareSubQueryImplicitConversion(){
+        String sql = "select e1 from pm1.g1 where e1 < (select e2 from pm4.g1 where e1 = '3')"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    } 
+
+    @Test public void testExistsSubQuery(){
+        String sql = "select e1 from pm1.g1 where exists (select e2 from pm4.g1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    } 
+
+    @Test public void testExistsSubQuery2(){
+        String sql = "select e1 from pm1.g1 where exists (select e1, e2 from pm4.g1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    } 
+
+    @Test public void testScalarSubQueryInSelect(){
+        String sql = "select e1, (select e2 from pm4.g1 where e1 = '3') from pm1.g1"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    } 
+
+    @Test public void testScalarSubQueryInSelect2(){
+        String sql = "select (select e2 from pm4.g1 where e1 = '3'), e1 from pm1.g1"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    } 
+
+    @Test public void testScalarSubQueryInSelectWithAlias(){
+        String sql = "select e1, (select e2 from pm4.g1 where e1 = '3') as X from pm1.g1"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    } 
+
+    @Test public void testSelectWithNoFrom() {
+        String sql = "SELECT 5"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testSelectWithNoFrom_Alias() {
+        String sql = "SELECT 5 AS INTKEY"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testSelectWithNoFrom_Alias_OrderBy() {
+        String sql = "SELECT 5 AS INTKEY ORDER BY INTKEY"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testSubqueryCorrelatedInCriteria(){
+        String sql = "select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1 where pm1.g1.e1 = pm4.g1.e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"pm1.g1.e1"}); //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryCorrelatedInCriteria2(){
+        String sql = "select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1 where pm1.g1.e1 = e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"pm1.g1.e1"}); //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryCorrelatedInCriteria3(){
+        String sql = "select e1 from pm1.g1 X where e2 = all (select e2 from pm4.g1 where X.e1 = pm4.g1.e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
+    }
+    
+    @Test public void testSubqueryCorrelatedInCriteria4(){
+        String sql = "select e2 from pm1.g1 X where e2 in (select e2 from pm1.g1 Y where X.e1 = Y.e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
+    }    
+
+    @Test public void testSubqueryCorrelatedInCriteria5(){
+        String sql = "select e1 from pm1.g1 X where e2 = all (select e2 from pm1.g1 Y where X.e1 = e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
+    }    
+
+    /* 'e5' is only in pm4.g2 */
+    @Test public void testSubqueryCorrelatedInCriteria6(){
+        String sql = "select e1 from pm4.g2 where e2 = some (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+    }
+
+    /* 'e5' is only in pm4.g2 */
+    @Test public void testSubqueryCorrelatedInCriteria7(){
+        String sql = "select e1 from pm4.g2 where exists (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryCorrelatedInHaving(){
+        String sql = "select e1, e2 from pm4.g2 group by e2 having e2 in (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryCorrelatedInHaving2(){
+        String sql = "select e1, e2 from pm4.g2 group by e2 having e2 <= all (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+    }
+
+    /* 'e5' is only in pm4.g2 */
+    @Test public void testSubqueryCorrelatedInSelect(){
+        String sql = "select e1, (select e2 from pm4.g1 where e5 = e1) from pm4.g2"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryCorrelatedInSelect2(){
+        String sql = "select e1, (select e2 from pm4.g1 where pm4.g2.e5 = e1) from pm4.g2"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryCorrelatedInSelect3(){
+        String sql = "select e1, (select e2 from pm4.g1 Y where X.e5 = Y.e1) from pm4.g2 X"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"X.e5"}); //$NON-NLS-1$
+    }
+
+    /* 'e5' is only in pm4.g2 */
+    @Test public void testNestedCorrelatedSubqueries(){
+        String sql = "select e1, (select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1 where e5 = e1)) from pm4.g2"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+    }
+
+    /**
+     * 'e5' is in pm4.g2, so it will be resolved to the group aliased as 'Y'
+     */
+    @Test public void testNestedCorrelatedSubqueries2(){
+        String sql = "select e1, (select e2 from pm4.g2 Y where e2 = all (select e2 from pm4.g1 where e5 = e1)) from pm4.g2 X"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"Y.e5"}); //$NON-NLS-1$
+    }
+
+    /**
+     *  'e5' is in pm4.g2; it will be resolved to the group aliased as 'X' 
+     */
+    @Test public void testNestedCorrelatedSubqueries3(){
+        String sql = "select e1, (select e2 from pm4.g2 Y where e2 = all (select e2 from pm4.g1 where X.e5 = e1)) from pm4.g2 X"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"X.e5"}); //$NON-NLS-1$
+    }
+
+    /**
+     *  'e5' is in X and Y 
+     */
+    @Test public void testNestedCorrelatedSubqueries4(){
+        String sql = "select X.e2 from pm4.g2 Y, pm4.g2 X where X.e2 = all (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+        helpResolveException(sql, metadata, "Element \"e5\" is ambiguous, it exists in two or more groups."); //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryCorrelatedInCriteriaVirtualLayer(){
+        String sql = "select e2 from vm1.g1 where e2 = all (select e2 from vm1.g2 where vm1.g1.e1 = vm1.g2.e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"vm1.g1.e1"}); //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryCorrelatedInCriteriaVirtualLayer2(){
+        String sql = "select e2 from vm1.g1 X where e2 = all (select e2 from vm1.g2 where X.e1 = vm1.g2.e1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
+    }
+
+    /** 
+     * Although this query makes no sense, the "e1" in the nested criteria is
+     * NOT a correlated reference 
+     */
+    @Test public void testSubqueryNonCorrelatedInCriteria(){
+        String sql = "select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    }
+
+    /** 
+     * Although this query makes no sense, the "e1" in the nested criteria is
+     * NOT a correlated reference 
+     */
+    @Test public void testSubqueryNonCorrelatedInCriteria2(){
+        String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1))"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    }
+
+    /** 
+     * Although this query makes no sense, the "e1" in the nested criteria is
+     * NOT a correlated reference 
+     */
+    @Test public void testSubqueryNonCorrelatedInCriteria3(){
+        String sql = "SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    }
+
+    /** 
+     * The group pm1.g1 in the FROM clause of the subquery should resolve to the 
+     * group in metadata, not the temporary child metadata group defined by the
+     * outer query.
+     */
+    @Test public void testSubquery_defect10090(){
+        String sql = "select pm1.g1.e1 from pm1.g1 where pm1.g1.e2 in (select pm1.g1.e2 from pm1.g1 where pm1.g1.e4 = 2.0)";  //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    }
+
+    /**
+     * Workaround is to alias group in FROM of outer query (aliasing subquery group doesn't work)
+     */
+    @Test public void testSubquery_defect10090Workaround(){
+        String sql = "select X.e1 from pm1.g1 X where X.e2 in (select pm1.g1.e2 from pm1.g1 where pm1.g1.e4 = 2.0)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    }
+
+    @Test public void testSubquery2_defect10090(){
+        String sql = "select pm1.g1.e1 from pm1.g1 where pm1.g1.e2 in (select X.e2 from pm1.g1 X where X.e4 = 2.0)"; //$NON-NLS-1$
+        this.helpResolveSubquery(sql, new String[0]);
+    }
+    
+    /** test jdbc USER method */
+    @Test public void testUser() {
+        //String sql = "select intkey from SmallA where user() = 'bqt2'";
+
+        // Expected left expression
+        FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();                          
+        FunctionDescriptor fd = library.findFunction(FunctionLibrary.USER, new Class[] { });
+        Function user = new Function(fd.getName(), new Expression[] {});
+        user.setFunctionDescriptor(fd);
+
+        // Expected criteria
+        CompareCriteria expected = new CompareCriteria();
+        // Expected right expression
+        Expression e1 = new Constant("bqt2", String.class); //$NON-NLS-1$
+        // Expected left expression
+        expected.setLeftExpression(user);
+        expected.setOperator(CompareCriteria.EQ);
+        expected.setRightExpression(e1);
+         
+        // Resolve the query and check against expected objects
+        CompareCriteria actual = (CompareCriteria) helpResolveCriteria("user()='bqt2'");    //$NON-NLS-1$
+        assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+    }
+    
+    @Test public void testCaseExpression1() {
+        String sql = "SELECT e1, CASE e2 WHEN 0 THEN 20 WHEN 1 THEN 21 WHEN 2 THEN 500 END AS testElement FROM pm1.g1" //$NON-NLS-1$
+                    +" WHERE e1 = CASE WHEN e2 = 0 THEN 'a' WHEN e2 = 1 THEN 'b' ELSE 'c' END"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    
+    @Test public void testCaseExpression2() {
+        // nested case expressions
+        String sql = "SELECT CASE e2" + //$NON-NLS-1$
+                                " WHEN 0 THEN CASE e1 " + //$NON-NLS-1$
+                                                " WHEN 'a' THEN 100" + //$NON-NLS-1$
+                                                " WHEN 'b' THEN 200 " + //$NON-NLS-1$
+                                                " ELSE 1000 " + //$NON-NLS-1$
+                                            " END" + //$NON-NLS-1$
+                                " WHEN 1 THEN 21" + //$NON-NLS-1$
+                                " WHEN (CASE WHEN e1 = 'z' THEN 2 WHEN e1 = 'y' THEN 100 ELSE 3 END) THEN 500" + //$NON-NLS-1$
+                           " END AS testElement FROM pm1.g1"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testCaseExpressionWithNestedFunction() {
+        String sql = "SELECT CASE WHEN e2 < 0 THEN abs(CASE WHEN e2 < 0 THEN -1 ELSE e2 END)" + //$NON-NLS-1$
+                           " ELSE e2 END FROM pm1.g1"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testFunctionWithNestedCaseExpression() {
+        String sql = "SELECT abs(CASE e1 WHEN 'testString1' THEN -13" + //$NON-NLS-1$
+                                       " WHEN 'testString2' THEN -5" + //$NON-NLS-1$
+                                       " ELSE abs(e2)" + //$NON-NLS-1$
+                               " END) AS absVal FROM pm1.g1"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+ 
+    @Test public void testDefect10809(){
+        String sql = "select * from LOB_TESTING_ONE where CLOB_COLUMN LIKE '%fff%'"; //$NON-NLS-1$
+        helpResolve(helpParse(sql), FakeMetadataFactory.exampleBQTCached(), AnalysisRecord.createNonRecordingRecord());
+    }
+    
+    @Test public void testNonAutoConversionOfLiteralIntegerToShort() throws Exception {       
+        // parse
+        Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE shortvalue = 5"); //$NON-NLS-1$
+        
+        // resolve
+        QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
+        
+        // Check whether an implicit conversion was added on the correct side
+        CompareCriteria crit = (CompareCriteria) command.getCriteria();
+         
+        assertEquals(DataTypeManager.DefaultDataClasses.SHORT, crit.getRightExpression().getType());
+        assertEquals("Sql is incorrect after resolving", "SELECT intkey FROM bqt1.smalla WHERE shortvalue = 5", command.toString()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testNonAutoConversionOfLiteralIntegerToShort2() throws Exception {       
+        // parse
+        Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE 5 = shortvalue"); //$NON-NLS-1$
+        
+        // resolve
+        QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
+        
+        // Check whether an implicit conversion was added on the correct side
+        CompareCriteria crit = (CompareCriteria) command.getCriteria();
+         
+        assertEquals(DataTypeManager.DefaultDataClasses.SHORT, crit.getLeftExpression().getType());
+        assertEquals("Sql is incorrect after resolving", "SELECT intkey FROM bqt1.smalla WHERE 5 = shortvalue", command.toString()); //$NON-NLS-1$ //$NON-NLS-2$
+    }               
+
+    @Test public void testAliasedOrderBy() {
+        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1 as y FROM pm1.g1 ORDER BY y"); //$NON-NLS-1$
+        helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+        helpCheckSelect(resolvedQuery, new String[] { "y" }); //$NON-NLS-1$
+    }        
+    
+    @Test public void testUnaliasedOrderBySucceeds() {
+        helpResolve("SELECT pm1.g1.e1 a, pm1.g1.e1 b FROM pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
+    }
+    
+    @Test public void testUnaliasedOrderBySucceeds1() {
+        helpResolve("SELECT pm1.g1.e1 a FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
+    }
+    
+    @Test public void testUnaliasedOrderByFails() {
+        helpResolveException("SELECT pm1.g1.e1 e2 FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e2"); //$NON-NLS-1$
+    }
+    
+    @Test public void testUnaliasedOrderByFails1() {
+        helpResolveException("SELECT pm1.g1.e1 e2 FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e2 + 1"); //$NON-NLS-1$
+    }
+
+    /** 
+     * the group g1 is not known to the order by clause of a union
+     */
+    @Test public void testUnionOrderByFail() {
+        helpResolveException("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY g1.e1", "ORDER BY expression 'g1.e1' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
+    }      
+    
+    @Test public void testUnionOrderByFail1() {
+        helpResolveException("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g1.e1", "ORDER BY expression 'pm1.g1.e1' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testOrderByPartiallyQualified() {
+        helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY g1.e1"); //$NON-NLS-1$
+    }
+    
+    /** 
+     * the group g1 is not known to the order by clause of a union
+     */
+    @Test public void testUnionOrderBy() {
+        helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY e1"); //$NON-NLS-1$
+    } 
+    
+    /** 
+     * Test for defect 12087 - Insert with implicit conversion from integer to short
+     */
+    @Test public void testImplConversionBetweenIntAndShort() throws Exception {       
+    	Insert command = (Insert)QueryParser.getQueryParser().parseCommand("Insert into pm5.g3(e2) Values(100)"); //$NON-NLS-1$
+        QueryResolver.resolveCommand(command, metadata);
+        assertTrue(((Expression)command.getValues().get(0)).getType() == DataTypeManager.DefaultDataClasses.SHORT);
+    }
+    
+    public static FakeMetadataFacade example_12968() { 
+        // Create models
+        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("myModel"); //$NON-NLS-1$
+        FakeMetadataObject pm2 = FakeMetadataFactory.createPhysicalModel("myModel2"); //$NON-NLS-1$
+        
+        FakeMetadataObject pm1g1 = FakeMetadataFactory.createPhysicalGroup("myModel.myTable", pm1); //$NON-NLS-1$
+        FakeMetadataObject pm2g1 = FakeMetadataFactory.createPhysicalGroup("myModel2.mySchema.myTable2", pm2); //$NON-NLS-1$
+        
+        List pm1g1e = FakeMetadataFactory.createElements(pm1g1, 
+            new String[] { "myColumn", "myColumn2" }, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        List pm2g1e = FakeMetadataFactory.createElements(pm2g1, 
+            new String[] { "myColumn", "myColumn2" }, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        
+        // Add all objects to the store
+        FakeMetadataStore store = new FakeMetadataStore();
+        store.addObject(pm1);
+        store.addObject(pm1g1);     
+        store.addObjects(pm1g1e);
+        store.addObject(pm2g1);     
+        store.addObjects(pm2g1e);
+        
+        return new FakeMetadataFacade(store);
+    }
+        
+    @Test public void testDefect12968_union() {
+        helpResolve(
+            helpParse("SELECT myModel.myTable.myColumn AS myColumn from myModel.myTable UNION " + //$NON-NLS-1$
+                "SELECT convert(null, string) AS myColumn From myModel2.mySchema.myTable2"),  //$NON-NLS-1$
+            example_12968(), AnalysisRecord.createNonRecordingRecord());
+    }
+
+
+    @Test public void testUnionQueryWithNull() throws Exception{
+    	helpResolve("SELECT NULL, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
+    	helpResolve("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT NULL, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
+    	helpResolve("SELECT e1, NULL FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
+    	helpResolve("SELECT e1, NULL FROM pm1.g2 UNION ALL SELECT e1, NULL FROM pm1.g3"); //$NON-NLS-1$
+    	helpResolve("SELECT e1, NULL as e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
+    	helpResolve("SELECT e1, NULL as e2 FROM pm1.g1 UNION ALL SELECT e1, e3 FROM pm1.g2"); //$NON-NLS-1$
+    }
+    
+    @Test public void testUnionQueryWithDiffTypes() throws Exception{
+        helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2"); //$NON-NLS-1$
+        helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2 UNION ALL SELECT NULL, e3 FROM pm1.g2");      //$NON-NLS-1$
+        helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e3, e3 FROM pm1.g2 UNION ALL SELECT NULL, e3 FROM pm1.g2");      //$NON-NLS-1$
+        helpResolve("SELECT e1, e2 FROM pm1.g3 UNION ALL SELECT MAX(e4), e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
+        helpResolve("SELECT e1, e4 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2"); //$NON-NLS-1$
+        helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
+        helpResolve("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e3, e4 FROM pm1.g2");   //$NON-NLS-1$
+        helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g2");  //$NON-NLS-1$
+        helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e1, e2 FROM pm1.g2"); //$NON-NLS-1$
+        helpResolve("SELECT MAX(e4), e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
+        //chooses a common type
+        helpResolve("select e2 from pm3.g1 union select e3 from pm3.g1 union select e4 from pm3.g1"); //$NON-NLS-1$
+    } 
+    
+    @Test public void testUnionQueryWithDiffTypesFails() throws Exception{
+        helpResolveException("SELECT e1 FROM pm1.g1 UNION (SELECT e2 FROM pm1.g2 UNION SELECT e2 from pm1.g1 order by e2)", "The Expression e2 used in a nested UNION ORDER BY clause cannot be implicitly converted from type integer to type string."); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testNestedUnionQueryWithNull() throws Exception{
+        SetQuery command = (SetQuery)helpResolve("SELECT e2, e3 FROM pm1.g1 UNION (SELECT null, e3 FROM pm1.g2 UNION SELECT null, e3 from pm1.g1)"); //$NON-NLS-1$
+        
+        assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(0)).getType());
+    }
+    
+    @Test public void testUnionQueryClone() throws Exception{
+        SetQuery command = (SetQuery)helpResolve("SELECT e2, e3 FROM pm1.g1 UNION SELECT e3, e2 from pm1.g1"); //$NON-NLS-1$
+        
+        assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(1)).getType());
+        
+        command = (SetQuery)command.clone();
+        
+        assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(1)).getType());
+    }
+    
+    @Test public void testSelectIntoNoFrom() {
+        helpResolve("SELECT 'a', 19, {b'true'}, 13.999 INTO pm1.g1"); //$NON-NLS-1$
+    }
+    
+    @Test public void testSelectInto() {
+        helpResolve("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2"); //$NON-NLS-1$
+    }
+    
+    @Test public void testSelectIntoTempGroup() {
+        helpResolve("SELECT 'a', 19, {b'true'}, 13.999 INTO #myTempTable"); //$NON-NLS-1$
+        helpResolve("SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g1"); //$NON-NLS-1$
+    }
+                
+    //procedural relational mapping
+    @Test public void testProcInVirtualGroup1(){
+        String sql = "select e1 from pm1.vsp26 where param1=1 and param2='a'"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testProcInVirtualGroup2(){
+        String sql = "select * from pm1.vsp26 as p where param1=1 and param2='a'"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testProcInVirtualGroup3(){
+        String sql = "SELECT P.e1 as ve3 FROM pm1.vsp26 as P, pm1.g2 where P.e1=g2.e1 and param1=1 and param2='a'"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testProcInVirtualGroup4(){
+        String sql = "SELECT P.e1 as ve3 FROM pm1.vsp26 as P, vm1.g1 where P.e1=g1.e1 and param1=1 and param2='a'"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testProcInVirtualGroup5(){
+        String sql = "SELECT * FROM (SELECT p.* FROM pm1.vsp26 as P, vm1.g1 where P.e1=g1.e1) x where param1=1 and param2='a'"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testProcInVirtualGroup6(){
+        String sql = "SELECT P.e1 as ve3, P.e2 as ve4 FROM pm1.vsp26 as P where param1=1 and param2='a'"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+
+    @Test public void testProcInVirtualGroup7(){
+        String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P where param1=1 and param2='a'"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+
+    @Test public void testProcInVirtualGroup7a(){
+        String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P where param1=1"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+        
+    @Test public void testProcParamComparison_defect13653() {
+        String userSql = "SELECT * FROM (EXEC mmspTest1.MMSP5('a')) AS a, (EXEC mmsptest1.mmsp6('b')) AS b"; //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        AnalysisRecord analysis = AnalysisRecord.createNonRecordingRecord();
+        
+        Query query = (Query) helpResolve(userSql, metadata, analysis);
+        From from = query.getFrom();
+        Collection fromClauses = from.getClauses();
+        SPParameter params[] = new SPParameter[2];
+        Iterator iter = fromClauses.iterator();
+        while(iter.hasNext()) {
+            SubqueryFromClause clause = (SubqueryFromClause) iter.next();
+            StoredProcedure proc = (StoredProcedure) clause.getCommand();
+            List procParams = proc.getParameters();
+            for(int i=0; i<procParams.size(); i++) {
+                SPParameter param = (SPParameter) procParams.get(i);
+                if(param.getParameterType() == ParameterInfo.IN) {
+                    if(params[0] == null) {
+                        params[0] = param;
+                    } else {
+                        params[1] = param;
+                    }
+                }
+            }
+        }
+        
+        assertTrue("Params should be not equal", ! params[0].equals(params[1])); //$NON-NLS-1$
+    }
+    
+    @Test public void testNullConstantInSelect() throws Exception {
+        String userSql = "SELECT null as x"; //$NON-NLS-1$
+        Query query = (Query)helpParse(userSql);
+        
+        QueryResolver.resolveCommand(query, FakeMetadataFactory.exampleBQTCached(), AnalysisRecord.createNonRecordingRecord());
+        
+        // Check type of resolved null constant
+        SingleElementSymbol symbol = (SingleElementSymbol) query.getSelect().getSymbols().get(0);
+        assertNotNull(symbol.getType());
+        assertEquals(DataTypeManager.DefaultDataClasses.STRING, symbol.getType());
+    }
+
+    @Test public void test11716() throws Exception {
+    	String sql = "SELECT e1 FROM pm1.g1 where e1='1'"; //$NON-NLS-1$
+    	Map externalMetadata = new HashMap();
+    	GroupSymbol inputSet = new GroupSymbol("INPUT"); //$NON-NLS-1$
+    	List inputSetElements = new ArrayList();
+    	ElementSymbol inputSetElement = new ElementSymbol("INPUT.e1"); //$NON-NLS-1$
+    	inputSetElements.add(inputSetElement);
+    	externalMetadata.put(inputSet, inputSetElements);
+        Query command = (Query)helpParse(sql);
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+        Collection groups = GroupCollectorVisitor.getGroups(command, false);
+        assertFalse(groups.contains(inputSet));
+    }
+    
+    @Test public void testDefect15872() throws Exception {
+    	String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
+    		+ "BEGIN " //$NON-NLS-1$
+			+"SELECT * FROM pm1.g1 where model.table.param=e1; " //$NON-NLS-1$
+			+"end "; //$NON-NLS-1$
+        Command command = helpParse(sql);
+    	Map externalMetadata = new HashMap();
+    	GroupSymbol procGroup = new GroupSymbol("model.table"); //$NON-NLS-1$
+    	List procPrarms = new ArrayList();
+    	ElementSymbol param = new ElementSymbol("model.table.param"); //$NON-NLS-1$
+    	param.setType(String.class);
+    	procPrarms.add(param);
+    	externalMetadata.put(procGroup, procPrarms);
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+        CreateUpdateProcedureCommand proc = (CreateUpdateProcedureCommand)command;
+        Query query = (Query)proc.getSubCommands().get(0);
+        ElementSymbol inElement = (ElementSymbol)((CompareCriteria)query.getCriteria()).getLeftExpression();
+        assertNotNull("Input parameter does not have group", inElement.getGroupSymbol()); //$NON-NLS-1$
+    }
+    
+    @Test public void testInputToInputsConversion() 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 + "ROWS_UPDATED = (Select pm1.g1.e2 from pm1.g1 where e2=INPUTS.e2);\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
+        
+        Command command = helpResolveUpdateProcedure(procedure, userUpdateStr);
+        assertEquals("CREATE PROCEDURE\nBEGIN\nDECLARE integer var1;\nROWS_UPDATED = (SELECT pm1.g1.e2 FROM pm1.g1 WHERE e2 = INPUTS.e2);\nEND", command.toString());
+    }
+    
+    @Test public void testDefect16894_resolverException_1() {
+        helpResolve("SELECT * FROM (SELECT * FROM Pm1.g1 AS Y) AS X"); //$NON-NLS-1$
+    }
+
+    @Test public void testDefect16894_resolverException_2() {
+        helpResolve("SELECT * FROM (SELECT * FROM Pm1.g1) AS X"); //$NON-NLS-1$
+    }
+
+    @Test public void testDefect17385() throws Exception{  
+		String sql = "select e1 as x ORDER BY x"; //$NON-NLS-1$      
+		helpResolveException(sql);
+	}
+    
+    @Test public void testValidFullElementNotInQueryGroups() {
+        helpResolveException("select pm1.g1.e1 FROM pm1.g1 g"); //$NON-NLS-1$
+    }
+    
+    @Test public void testUnionInSubquery() throws Exception {
+        String sql = "SELECT StringKey FROM (SELECT BQT2.SmallB.StringKey FROM BQT2.SmallB union SELECT convert(BQT2.SmallB.FloatNum, string) FROM BQT2.SmallB) x";  //$NON-NLS-1$
+        Command command = QueryParser.getQueryParser().parseCommand(sql);
+        QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
+    }
+
+    @Test public void testParameterError() throws Exception {
+        helpResolveException("EXEC pm1.sp2(1, 2)", metadata, "Error Code:ERR.015.008.0007 Message:Incorrect number of parameters specified on the stored procedure pm1.sp2 - expected 1 but got 2"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testUnionOfAliasedLiteralsGetsModified() {
+        String sql = "SELECT 5 AS x UNION ALL SELECT 10 AS x"; //$NON-NLS-1$
+        Command c = helpResolve(sql); 
+        assertEquals(sql, c.toString());
+    }
+    
+    @Test public void testXMLWithProcSubquery() {
+        String sql = "SELECT * FROM xmltest.doc4 WHERE node2 IN (SELECT e1 FROM (EXEC pm1.vsp1()) AS x)"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        assertEquals(sql, c.toString());
+    }
+    
+    @Test public void testDefect18832() {
+        String sql = "SELECT * from (SELECT null as a, e1 FROM pm1.g1) b"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        List projectedSymbols = c.getProjectedSymbols();
+        for(int i=0; i< projectedSymbols.size(); i++) {
+            ElementSymbol symbol = (ElementSymbol)projectedSymbols.get(i);
+            assertTrue(!symbol.getType().equals(DataTypeManager.DefaultDataClasses.NULL));           
+        }
+    }
+    
+    @Test public void testDefect18832_2() {
+        String sql = "SELECT a.*, b.* from (SELECT null as a, e1 FROM pm1.g1) a, (SELECT e1 FROM pm1.g1) b"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        List projectedSymbols = c.getProjectedSymbols();
+        for(int i=0; i< projectedSymbols.size(); i++) {
+            ElementSymbol symbol = (ElementSymbol)projectedSymbols.get(i);
+            assertTrue(!symbol.getType().equals(DataTypeManager.DefaultDataClasses.NULL));           
+        }
+    }
+    
+    @Test public void testDefect20113() {
+        String sql = "SELECT g1.* from pm1.g1"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+
+    @Test public void testDefect20113_2() {
+        String sql = "SELECT g7.* from g7"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    private void verifyProjectedTypes(Command c, Class[] types) {
+        List projSymbols = c.getProjectedSymbols();
+        for(int i=0; i<projSymbols.size(); i++) {
+            assertEquals("Found type mismatch at column " + i, types[i], ((SingleElementSymbol) projSymbols.get(i)).getType()); //$NON-NLS-1$
+        }                
+    }
+    
+    @Test public void testNestedInlineViews() throws Exception {
+        String sql = "SELECT * FROM (SELECT * FROM (SELECT * FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        assertEquals(sql, c.toString());
+        
+        verifyProjectedTypes(c, new Class[] { String.class, Integer.class, Boolean.class, Double.class });
+    }
+
+    @Test public void testNestedInlineViewsNoStar() throws Exception {
+        String sql = "SELECT e1 FROM (SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        assertEquals(sql, c.toString());      
+        
+        verifyProjectedTypes(c, new Class[] { String.class });
+    }
+
+    @Test public void testNestedInlineViewsCount() throws Exception {
+        String sql = "SELECT COUNT(*) FROM (SELECT * FROM (SELECT * FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        assertEquals(sql, c.toString());        
+        verifyProjectedTypes(c, new Class[] { Integer.class });
+    }
+    
+    @Test public void testAggOverInlineView() throws Exception {
+        String sql = "SELECT SUM(x) FROM (SELECT (e2 + 1) AS x FROM pm1.g1) AS g"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        assertEquals(sql, c.toString());        
+        verifyProjectedTypes(c, new Class[] { Long.class });
+        
+    }
+
+    @Test public void testCaseOverInlineView() throws Exception {
+        String sql = "SELECT CASE WHEN x > 0 THEN 1.0 ELSE 2.0 END FROM (SELECT e2 AS x FROM pm1.g1) AS g"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        assertEquals(sql, c.toString());        
+        verifyProjectedTypes(c, new Class[] { Double.class });
+        
+    }
+    
+    //procedure - select * from temp table 
+    @Test public void testDefect20083_1 (){
+        helpResolve("EXEC pm1.vsp56()");   //$NON-NLS-1$
+    }
+    
+    //procedure - select * from temp table order by
+    @Test public void testDefect20083_2 (){
+        helpResolve("EXEC pm1.vsp57()");   //$NON-NLS-1$
+    }
+    
+    @Test public void testTypeConversionOverUnion() throws Exception { 
+        String sql = "SELECT * FROM (SELECT e2, e1 FROM pm1.g1 UNION SELECT convert(e2, string), e1 FROM pm1.g1) FOO where e2/2 = 1"; //$NON-NLS-1$ 
+        helpResolveException(sql); 
+    }
+    
+    @Test public void testVariableDeclarationAfterStatement() throws Exception{
+        String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "select * from pm1.g1 where pm1.g1.e1 = VARIABLES.X;\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE string VARIABLES.X = 1;\n";         //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        helpResolveException(procedure, "Element \"VARIABLES.X\" is not defined by any relevant group."); //$NON-NLS-1$
+    }
+    
+    /**
+     * same as above, but with an xml query 
+     * @throws Exception
+     */
+    @Test public void testVariableDeclarationAfterStatement1() throws Exception{
+        String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "select * from xmltest.doc1 where node1 = VARIABLES.X;\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE string VARIABLES.X = 1;\n";         //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        helpResolveException(procedure, "Error Code:ERR.015.008.0019 Message:Unable to resolve element: VARIABLES.X"); //$NON-NLS-1$
+    }
+    
+    @Test public void testCreate() {
+        String sql = "CREATE LOCAL TEMPORARY TABLE temp_table (column1 string)"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        assertEquals(sql, c.toString());  
+    }
+    
+    @Test public void testCreateQualifiedName() {
+        String sql = "CREATE LOCAL TEMPORARY TABLE pm1.g1 (column1 string)"; //$NON-NLS-1$
+        helpResolveException(sql, "Cannot create temporary table \"pm1.g1\". Local temporary tables must be created with unqualified names."); //$NON-NLS-1$
+    }
+
+    @Test public void testCreatePk() {
+        String sql = "CREATE LOCAL TEMPORARY TABLE foo (column1 string, column2 integer, primary key (column1, column2))"; //$NON-NLS-1$
+        helpResolve(sql);
+    }
+    
+    @Test public void testCreateUnknownPk() {
+        String sql = "CREATE LOCAL TEMPORARY TABLE foo (column1 string, primary key (column2))"; //$NON-NLS-1$
+        helpResolveException(sql, "Element \"column2\" is not defined by any relevant group."); //$NON-NLS-1$
+    }
+
+    @Test public void testCreateAlreadyExists() {
+        String sql = "CREATE LOCAL TEMPORARY TABLE g1 (column1 string)"; //$NON-NLS-1$
+        helpResolveException(sql, "Cannot create temporary table \"g1\". A table with the same name already exists."); //$NON-NLS-1$
+    }
+
+    @Test public void testCreateImplicitName() {
+        String sql = "CREATE LOCAL TEMPORARY TABLE #g1 (column1 string)"; //$NON-NLS-1$
+        Command c = helpResolve(sql);
+        assertEquals(sql, c.toString());
+    }
+    
+    @Test public void testCreateInProc() throws Exception{
+        helpResolveException("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table g1(c1 string); end", "Cannot create temporary table \"g1\". A table with the same name already exists.");//$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    //this was the old virt.agg procedure.  It was defined in such a way that relied on the scope leak of #temp
+    //the exception here is a little weak since there are multiple uses of #temp in the block
+    @Test public void testTempTableScope() {
+        String proc =  "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
+            + "BEGIN " //$NON-NLS-1$
+            + "        DECLARE integer VARIABLES.BITS;" //$NON-NLS-1$
+            + "        LOOP ON (SELECT DISTINCT phys.t.ID, phys.t.Name FROM phys.t) AS idCursor" //$NON-NLS-1$
+            + "        BEGIN" //$NON-NLS-1$
+            + "                VARIABLES.BITS = 0;" //$NON-NLS-1$
+            + "                LOOP ON (SELECT phys.t.source_bits FROM phys.t WHERE phys.t.ID = idCursor.id) AS bitsCursor" //$NON-NLS-1$
+            + "                BEGIN" //$NON-NLS-1$
+            + "                        VARIABLES.BITS = bitor(VARIABLES.BITS, bitsCursor.source_bits);" //$NON-NLS-1$
+            + "                END" //$NON-NLS-1$
+            + "                SELECT idCursor.id, idCursor.name, VARIABLES.BITS INTO #temp;" //$NON-NLS-1$
+            + "        END" //$NON-NLS-1$
+            + "        SELECT ID, Name, #temp.BITS AS source_bits FROM #temp;" //$NON-NLS-1$                                          
+            + "END"; //$NON-NLS-1$ 
+        
+        helpResolveException(proc, FakeMetadataFactory.exampleBitwise(), "Group does not exist: #temp"); //$NON-NLS-1$
+    }
+    
+    @Test public void testDrop() {
+        String sql = "DROP TABLE temp_table"; //$NON-NLS-1$
+        helpResolveException(sql, "Group does not exist: temp_table"); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testResolveUnqualifiedCriteria() throws Exception{
+        Criteria criteria = QueryParser.getQueryParser().parseCriteria("e1 = 1"); //$NON-NLS-1$
+           
+        // resolve
+        try { 
+            QueryResolver.resolveCriteria(criteria, metadata);
+            fail("Exception expected"); //$NON-NLS-1$
+        } catch(QueryResolverException e) {
+            assertEquals("Symbol e1 is specified with an unknown group context", e.getMessage()); //$NON-NLS-1$
+        } 
+    }
+    
+    @Test public void testSameNameRoot() {
+        String sql = "select p.e1 from pm1.g1 as pp, pm1.g1 as p"; //$NON-NLS-1$
+        
+        helpResolve(sql);
+    }
+    
+    @Test public void testDefect23342() throws Exception {
+        String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
+            + "BEGIN " //$NON-NLS-1$
+            + "IF (param = '1')" //$NON-NLS-1$
+            + " BEGIN " //$NON-NLS-1$
+            +"SELECT * FROM pm1.g1 where model.table.param=e1; " //$NON-NLS-1$
+            +" END " //$NON-NLS-1$
+            +"end "; //$NON-NLS-1$
+        Command command = helpParse(sql);
+        Map externalMetadata = new HashMap();
+        GroupSymbol proc = new GroupSymbol("model.table"); //$NON-NLS-1$
+        List procPrarms = new ArrayList();
+        ElementSymbol param = new ElementSymbol("model.table.param"); //$NON-NLS-1$
+        param.setType(DataTypeManager.DefaultDataClasses.STRING);
+        procPrarms.add(param);
+        externalMetadata.put(proc, procPrarms);
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+    }
+        
+    @Test public void testBatchedUpdateResolver() throws Exception {
+        String update1 = "update pm1.g1 set e1 =1"; //$NON-NLS-1$
+        String update2 = "update pm2.g1 set e1 =1"; //$NON-NLS-1$
+        
+        List commands = new ArrayList();
+        commands.add(QueryParser.getQueryParser().parseCommand(update1));
+        commands.add(QueryParser.getQueryParser().parseCommand(update2));
+        BatchedUpdateCommand command = new BatchedUpdateCommand(commands);
+        
+        helpResolve(command);
+    }
+    
+    @Test public void testAmbiguousAllInGroup() {
+        String sql = "SELECT g1.* from pm1.g1, pm2.g1"; //$NON-NLS-1$
+        helpResolveException(sql, metadata, "The symbol g1.* refers to more than one group defined in the FROM clause."); //$NON-NLS-1$
+    }
+    
+    @Test public void testRowsUpdatedInProcedure(){
+        String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
+            + "BEGIN " //$NON-NLS-1$
+            +"SELECT ROWS_UPDATED; " //$NON-NLS-1$
+            +"end "; //$NON-NLS-1$
+        
+        helpResolveException(sql, metadata, "Element \"ROWS_UPDATED\" is not defined by any relevant group."); //$NON-NLS-1$
+    }
+    
+    @Test public void testXMLQueryWithVariable() {
+        String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
+            + "BEGIN " //$NON-NLS-1$
+            + "declare string x = '1'; " //$NON-NLS-1$
+            +"select * from xmltest.doc1 where node1 = x; " //$NON-NLS-1$
+            +"end "; //$NON-NLS-1$
+
+        CreateUpdateProcedureCommand command = (CreateUpdateProcedureCommand) helpResolve(sql); 
+        
+        CommandStatement cmdStmt = (CommandStatement)command.getBlock().getStatements().get(1);
+        
+        CompareCriteria criteria = (CompareCriteria)((Query)cmdStmt.getCommand()).getCriteria();
+        
+        assertEquals(ProcedureReservedWords.VARIABLES, ((ElementSymbol)criteria.getRightExpression()).getGroupSymbol().getCanonicalName());
+    }
+    
+    /**
+     *  We could check to see if the expressions are evaluatable to a constant, but that seems unnecessary
+     */
+    @Test public void testLookupWithoutConstant() throws Exception{
+        String sql = "SELECT lookup('pm1.g1', convert('e3', float), 'e2', e2) FROM pm1.g1"; //$NON-NLS-1$
+        
+        helpResolveException(sql, metadata, "Error Code:ERR.015.008.0063 Message:The first three arguments for the LOOKUP function must be specified as constants."); //$NON-NLS-1$
+    }
+    
+    /**
+     * We cannot implicitly convert the argument to double due to lack of precision
+     */
+    @Test public void testPowerWithBigInteger_Fails() throws Exception {
+        String sql = "SELECT power(10, 999999999999999999999999999999999999999999999)"; //$NON-NLS-1$
+        
+        helpResolveException(sql);
+    }
+    
+    @Test public void testPowerWithLong_Fails() throws Exception {
+        String sql = "SELECT power(10, 999999999999)"; //$NON-NLS-1$
+        
+        helpResolveException(sql);
+    }
+    
+    @Test public void testUpdateError() {
+        String userUpdateStr = "UPDATE vm1.g2 SET e1='x'"; //$NON-NLS-1$
+        
+        helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Update is not allowed on the view vm1.g2: a procedure must be defined to handle the Update."); //$NON-NLS-1$
+    }
+    
+    @Test public void testInsertError() {
+        String userUpdateStr = "INSERT into vm1.g2 (e1) values ('x')"; //$NON-NLS-1$
+        
+        helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Insert is not allowed on the view vm1.g2: a procedure must be defined to handle the Insert."); //$NON-NLS-1$
+    }
+    
+    @Test public void testDeleteError() {
+        String userUpdateStr = "DELETE from vm1.g2 where e1='x'"; //$NON-NLS-1$
+        
+        helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Delete is not allowed on the view vm1.g2: a procedure must be defined to handle the Delete."); //$NON-NLS-1$
+    }
+                
+    @Test public void testResolveXMLSelect() {
+        String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE string VARIABLES.X = 1;\n";         //$NON-NLS-1$
+        procedure = procedure + "select VARIABLES.X from xmltest.doc1;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n";         //$NON-NLS-1$
+
+        helpResolveException(procedure, "Error Code:ERR.015.008.0019 Message:Unable to resolve element: VARIABLES.X"); //$NON-NLS-1$
+    }
+    
+    @Test public void testXMLJoinFail() {
+        String query = "select * from xmltest.doc1, xmltest.doc2"; //$NON-NLS-1$
+         
+        helpResolveException(query, "Error Code:ERR.015.008.0003 Message:Only one XML document may be specified in the FROM clause of a query."); //$NON-NLS-1$
+    }
+    
+    @Test public void testExecProjectedSymbols() {
+        String query = "exec pm1.sq1()"; //$NON-NLS-1$
+         
+        StoredProcedure proc = (StoredProcedure)helpResolve(query); 
+        
+        List projected = proc.getProjectedSymbols();
+        
+        assertEquals(2, projected.size());
+        
+        for (Iterator i = projected.iterator(); i.hasNext();) {
+            ElementSymbol symbol = (ElementSymbol)i.next();
+            assertNotNull(symbol.getGroupSymbol());
+        }
+    }
+    
+    @Test public void testExecWithDuplicateNames() {
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        
+        FakeMetadataStore store = metadata.getStore();
+        
+        FakeMetadataObject pm1 = store.findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        
+        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "in", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
+        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
+        QueryNode sq2n1 = new QueryNode("pm1.sq2", "CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq2.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
+
+        store.addObject(rs2);
+        store.addObject(sq2);
+        
+        helpResolveException("select * from pm1.sq2", metadata, "Cannot access procedure pm1.sq2 using table semantics since the parameter and result set column names are not all unique."); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInlineViewNullLiteralInUnion() {
+        String sql = "select e2 from pm1.g1 union all (select x from (select null as x) y)"; //$NON-NLS-1$
+        
+        helpResolve(sql);
+    }
+    
+    @Test public void testSelectIntoWithDuplicateNames() {
+        String sql = "select 1 as x, 2 as x into #temp"; //$NON-NLS-1$
+        
+        helpResolveException(sql, "Cannot create group '#temp' with multiple columns named 'x'"); //$NON-NLS-1$
+    }
+    
+    @Test public void testCreateWithDuplicateNames() {
+        String sql = "CREATE LOCAL TEMPORARY TABLE temp_table (column1 string, column1 string)"; //$NON-NLS-1$
+        
+        helpResolveException(sql, "Cannot create group \'temp_table\' with multiple columns named \'column1\'"); //$NON-NLS-1$
+    }
+    
+    @Test public void testXMLQuery4() {
+        helpResolveException("SELECT * FROM xmltest.doc1 group by a2", "Queries against XML documents can not have a GROUP By clause"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testXMLQuery5() {
+        helpResolveException("SELECT * FROM xmltest.doc1 having a2='x'", "Queries against XML documents can not have a HAVING clause"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testSelectIntoWithOrderBy() {
+        String sql = "select e1, e2 into #temp from pm1.g1 order by e1 limit 10"; //$NON-NLS-1$
+        
+        helpResolve(sql);
+    }
+    
+    @Test public void testUnionBranchesWithDifferentElementCounts() {
+        helpResolveException("SELECT e2, e3 FROM pm1.g1 UNION SELECT e2 FROM pm1.g2","Queries combined with the set operator UNION must have the same number of output elements."); //$NON-NLS-1$ //$NON-NLS-2$
+        helpResolveException("SELECT e2 FROM pm1.g1 UNION SELECT e2, e3 FROM pm1.g2","Queries combined with the set operator UNION must have the same number of output elements."); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testSelectIntoWithNullLiteral() {
+        String sql = "select null as x into #temp from pm1.g1"; //$NON-NLS-1$
+        
+        Query query = (Query)helpResolve(sql);
+        
+        TempMetadataStore store = new TempMetadataStore(query.getTemporaryMetadata());
+        
+        TempMetadataID id = store.getTempElementID("#temp.x"); //$NON-NLS-1$
+        
+        assertEquals(DataTypeManager.DefaultDataClasses.STRING, id.getType());
+    }
+    
+    @Test public void testInsertWithNullLiteral() {
+        String sql = "insert into #temp (x) values (null)"; //$NON-NLS-1$
+        
+        Insert insert = (Insert)helpResolve(sql);
+        
+        TempMetadataStore store = new TempMetadataStore(insert.getTemporaryMetadata());
+        
+        TempMetadataID id = store.getTempElementID("#temp.x"); //$NON-NLS-1$
+        
+        assertEquals(DataTypeManager.DefaultDataClasses.STRING, id.getType());
+    }
+    
+    @Test public void testInsertWithoutColumnsFails() {
+        String sql = "Insert into pm1.g1 values (1, 2)"; //$NON-NLS-1$
+        
+        helpResolveException(sql, "Error Code:ERR.015.008.0010 Message:INSERT statement must have the same number of elements and values specified.  This statement has 4 elements and 2 values."); //$NON-NLS-1$
+    }
+    
+    @Test public void testInsertWithoutColumnsFails1() {
+        String sql = "Insert into pm1.g1 values (1, 2, 3, 4)"; //$NON-NLS-1$
+        
+        helpResolveException(sql, "Error Code:ERR.015.008.0041 Message:Expected value of type 'boolean' but '3' is of type 'integer' and no implicit conversion is available."); //$NON-NLS-1$
+    }
+    
+    @Test public void testInsertWithQueryFails() {
+        String sql = "Insert into pm1.g1 select 1, 2, 3, 4"; //$NON-NLS-1$
+        
+        helpResolveException(sql, "Cannot convert insert query expression projected symbol '3' of type java.lang.Integer to insert column 'pm1.g1.e3' of type java.lang.Boolean"); //$NON-NLS-1$
+    }
+    
+    @Test public void testInsertWithQueryImplicitWithoutColumns() {
+        String sql = "Insert into #X select 1 as x, 2 as y, 3 as z"; //$NON-NLS-1$
+        helpResolve(sql); //$NON-NLS-1$
+    }
+    
+    @Test public void testInsertWithQueryImplicitWithoutColumns1() {
+        String sql = "Insert into #X select 1 as x, 2 as y, 3 as y"; //$NON-NLS-1$
+        
+        helpResolveException(sql, "Cannot create group '#X' with multiple columns named 'y'"); //$NON-NLS-1$
+    }
+
+    @Test public void testInsertWithoutColumnsPasses() {
+        String sql = "Insert into pm1.g1 values (1, 2, true, 4)"; //$NON-NLS-1$
+        
+        helpResolve(sql);
+        Insert command = (Insert)helpResolve(sql);
+        assertEquals(4, command.getVariables().size());
+    }
+
+    @Test public void testInsertWithoutColumnsUndefinedTemp() {
+        String sql = "Insert into #temp values (1, 2)"; //$NON-NLS-1$
+
+        Insert command = (Insert)helpResolve(sql);
+        assertEquals(2, command.getVariables().size());
+    }
+    
+    @Test public void testImplicitTempInsertWithNoColumns() {
+        StringBuffer proc = new StringBuffer("CREATE VIRTUAL PROCEDURE") //$NON-NLS-1$
+        .append("\nBEGIN") //$NON-NLS-1$
+        .append("\n  create local temporary table #matt (x integer);") //$NON-NLS-1$
+        .append("\n  insert into #matt values (1);") //$NON-NLS-1$
+        .append("\nEND"); //$NON-NLS-1$
+        
+        Command cmd = helpResolve(proc.toString()); 
+
+        String sExpected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nCREATE LOCAL TEMPORARY TABLE #matt (x integer);\nINSERT INTO #matt (#MATT.x) VALUES (1);\nEND\n\tCREATE LOCAL TEMPORARY TABLE #matt (x integer)\n\tINSERT INTO #matt (#MATT.x) VALUES (1)\n";   //$NON-NLS-1$
+        String sActual = cmd.printCommandTree(); 
+        assertEquals( sExpected, sActual );
+    }
+
+    @Test public void testCase6319() throws QueryResolverException, TeiidComponentException {
+        String sql = "select floatnum from bqt1.smalla group by floatnum having sum(floatnum) between 51.0 and 100.0 "; //$NON-NLS-1$
+        Query query = (Query)helpParse(sql);
+        QueryResolver.resolveCommand(query, FakeMetadataFactory.exampleBQTCached());
+    }
+
+    @Test public void testUniqeNamesWithInlineView() {
+        helpResolveException("select * from (select count(intNum) a, count(stringKey) b, bqt1.smalla.intkey as b from bqt1.smalla group by bqt1.smalla.intkey) q1 order by q1.a", FakeMetadataFactory.exampleBQTCached(), "Cannot create group 'q1' with multiple columns named 'b'"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+            
+    @Test public void testResolveOldProcRelational() {
+        helpResolveException("SELECT * FROM pm1.g1, (exec pm1.sq2(pm1.g1.e1)) as a", "Symbol pm1.g1.e1 is specified with an unknown group context"); //$NON-NLS-1$  //$NON-NLS-2$
+    }
+    
+    @Test public void testResolverOrderOfPrecedence() {
+        helpResolveException("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 CROSS JOIN (pm1.g2 LEFT OUTER JOIN pm2.g1 on pm1.g1.e1 = pm2.g1.e1)", "Symbol pm1.g1.e1 is specified with an unknown group context"); //$NON-NLS-1$  //$NON-NLS-2$
+    }
+    
+    /**
+     * The cross join should parse/resolve with higher precedence
+     */
+    @Test public void testResolverOrderOfPrecedence_1() {
+        helpResolve("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 CROSS JOIN pm1.g2 LEFT OUTER JOIN pm2.g1 on pm1.g1.e1 = pm2.g1.e1"); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvalidColumnReferenceWithNestedJoin() {
+    	helpResolveException("SELECT a.* FROM (pm1.g2 a left outer join pm1.g2 b on a.e1= b.e1) LEFT OUTER JOIN (select a.e1) c on (a.e1 = c.e1)"); //$NON-NLS-1$ 
+    }
+    
+    /**
+     * should be the same as exec with too many params
+     */
+	@Test public void testCallableStatementTooManyParameters() throws Exception {
+		String sql = "{call pm4.spTest9(?, ?)}"; //$NON-NLS-1$
+		
+		TestResolver.helpResolveException(sql, FakeMetadataFactory.exampleBQTCached(), "Error Code:ERR.015.008.0007 Message:Incorrect number of parameters specified on the stored procedure pm4.spTest9 - expected 1 but got 2"); //$NON-NLS-1$
+	}	
+	    
+    @Test public void testUpdateSetClauseReferenceType() {
+    	String sql = "UPDATE pm1.g1 SET pm1.g1.e1 = 1, pm1.g1.e2 = ?;"; //$NON-NLS-1$
+    	
+    	Update update = (Update)helpResolve(sql, FakeMetadataFactory.example1Cached(), null);
+    	
+    	Expression ref = update.getChangeList().getClauses().get(1).getValue();
+    	assertTrue(ref instanceof Reference);
+    	assertNotNull(ref.getType());
+    }
+    
+    @Test public void testNoTypeCriteria() {
+    	String sql = "select * from pm1.g1 where ? = ?"; //$NON-NLS-1$
+    	
+    	helpResolveException(sql, FakeMetadataFactory.example1Cached(), "Error Code:ERR.015.008.0026 Message:Expression '? = ?' has a parameter with non-determinable type information.  The use of an explicit convert may be necessary."); //$NON-NLS-1$
+    }
+    
+    @Test public void testReferenceInSelect() {
+    	String sql = "select ?, e1 from pm1.g1"; //$NON-NLS-1$
+    	Query command = (Query)helpResolve(sql, FakeMetadataFactory.example1Cached(), null);
+    	assertEquals(DataTypeManager.DefaultDataClasses.STRING, ((SingleElementSymbol)command.getProjectedSymbols().get(0)).getType());
+    }
+    
+    @Test public void testReferenceInSelect1() {
+    	String sql = "select convert(?, integer), e1 from pm1.g1"; //$NON-NLS-1$
+    	
+    	Query command = (Query)helpResolve(sql, FakeMetadataFactory.example1Cached(), null);
+    	assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(0)).getType());
+    }
+    
+    @Test public void testUnionWithObjectTypeConversion() {
+    	String sql = "select convert(null, xml) from pm1.g1 union all select 1"; //$NON-NLS-1$
+    	
+    	SetQuery query = (SetQuery)helpResolve(sql, FakeMetadataFactory.example1Cached(), null);
+    	assertEquals(DataTypeManager.DefaultDataClasses.OBJECT, ((SingleElementSymbol)query.getProjectedSymbols().get(0)).getType());
+    }
+    
+    @Test public void testUnionWithSubQuery() {
+    	String sql = "select 1 from pm1.g1 where exists (select 1) union select 2"; //$NON-NLS-1$
+
+        SetQuery command = (SetQuery)helpResolve(sql);
+        
+        assertEquals(1, command.getSubCommands().size());
+    }
+    @Test public void testOrderBy_J658a() {
+        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY e3"); //$NON-NLS-1$
+        OrderBy orderBy = resolvedQuery.getOrderBy();
+        int[] expectedPositions = new int[] {2};
+        helpTestOrderBy(orderBy, expectedPositions);
+    }
+
+	private void helpTestOrderBy(OrderBy orderBy, int[] expectedPositions) {
+		assertEquals(expectedPositions.length, orderBy.getVariableCount());
+        for (int i = 0; i < expectedPositions.length; i++) {
+        	assertEquals(expectedPositions[i], orderBy.getExpressionPosition(i));
+        }
+	}
+    @Test public void testOrderBy_J658b() {
+        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY e2, e3 "); //$NON-NLS-1$
+        helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
+    }
+    @Test public void testOrderBy_J658c() {
+        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY x, e3 "); //$NON-NLS-1$
+        helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});    
+    }
+    
+    // ambiguous, should fail
+    @Test public void testOrderBy_J658d() {
+        helpResolveException("SELECT pm1.g1.e1, e2 as x, e3 as x FROM pm1.g1 ORDER BY x, e1 ", "Error Code:ERR.015.008.0042 Message:Element 'x' in ORDER BY is ambiguous and may refer to more than one element of SELECT clause."); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    @Test public void testOrderBy_J658e() {
+        Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as e2 FROM pm1.g1 ORDER BY x, e2 "); //$NON-NLS-1$
+        helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
+    }
+    
+    @Test public void testSPOutParamWithExec() {
+    	StoredProcedure proc = (StoredProcedure)helpResolve("exec pm2.spTest8(1)", FakeMetadataFactory.exampleBQTCached(), null);
+    	assertEquals(2, proc.getProjectedSymbols().size());
+    }
+
+    /**
+     * Note that the call syntax is not quite correct, the output parameter is not in the arg list.
+     * That hack is handled by the PreparedStatementRequest
+     */
+    @Test public void testSPOutParamWithCallableStatement() {
+    	StoredProcedure proc = (StoredProcedure)helpResolve("{call pm2.spTest8(1)}", FakeMetadataFactory.exampleBQTCached(), null);
+    	assertEquals(3, proc.getProjectedSymbols().size());
+    }
+    
+    @Test public void testOutWithWrongType() {
+    	helpResolveException("exec pm2.spTest8(inkey=>1, outkey=>{t '12:00:00'})", FakeMetadataFactory.exampleBQTCached());
+    }
+    
+    @Test public void testProcRelationalWithOutParam() {
+    	Query proc = (Query)helpResolve("select * from pm2.spTest8 where inkey = 1", FakeMetadataFactory.exampleBQTCached(), null);
+    	assertEquals(3, proc.getProjectedSymbols().size());
+    }
+    
+    @Test public void testSPReturnParamWithNoResultSet() {
+    	StoredProcedure proc = (StoredProcedure)helpResolve("exec pm4.spTest9(1)", FakeMetadataFactory.exampleBQTCached(), null);
+    	assertEquals(1, proc.getProjectedSymbols().size());
+    }
+    
+    @Test public void testSecondPassFunctionResolving() {
+    	helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where lower(?) = e1 "); //$NON-NLS-1$
+    }
+    
+    @Test public void testSecondPassFunctionResolving1() {
+    	try {
+    		helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where 1/(e1 - 2) <> 4 "); //$NON-NLS-1$
+    		fail("expected exception");
+    	} catch (RuntimeException e) {
+    		QueryResolverException qre = (QueryResolverException)e.getCause();
+    		assertEquals("ERR.015.008.0040", qre.getCode());
+    	}
+    }
+    
+    @Ignore("currently not supported - we get type hints from the criteria not from the possible signatures")
+    @Test public void testSecondPassFunctionResolving2() {
+    	helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where (lower(?) || 1) = e1 "); //$NON-NLS-1$
+    }
+
+    /**
+     * Test <code>QueryResolver</code>'s ability to resolve a query that 
+     * contains an aggregate <code>SUM</code> which uses a <code>CASE</code> 
+     * expression which contains <code>BETWEEN</code> criteria as its value.
+     * <p>
+     * For example:
+     * <p>
+     * SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1
+     */
+    @Test public void testAggregateWithBetweenInCaseInSelect() {
+    	String sql = "SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
+    	helpResolve(sql);
+    }
+    
+    /**
+     * Test <code>QueryResolver</code>'s ability to resolve a query that 
+     * contains a <code>CASE</code> expression which contains 
+     * <code>BETWEEN</code> criteria in the queries <code>SELECT</code> clause.
+     * <p>
+     * For example:
+     * <p>
+     * SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1
+     */
+    @Test public void testBetweenInCaseInSelect() {
+    	String sql = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
+    	helpResolve(sql);
+    }
+    
+    /**
+     * Test <code>QueryResolver</code>'s ability to resolve a query that 
+     * contains a <code>CASE</code> expression which contains 
+     * <code>BETWEEN</code> criteria in the queries <code>WHERE</code> clause.
+     * <p>
+     * For example:
+     * <p>
+     * SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END
+     */
+    @Test public void testBetweenInCase() {
+    	String sql = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END"; //$NON-NLS-1$
+    	helpResolve(sql);
+    }
+    
+    @Test public void testOrderByUnrelated() {
+        helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY e4"); //$NON-NLS-1$
+    }
+
+    @Test public void testOrderByUnrelated1() {
+        helpResolveException("SELECT distinct pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY e4"); //$NON-NLS-1$
+    }
+
+    @Test public void testOrderByUnrelated2() {
+        helpResolveException("SELECT max(e2) FROM pm1.g1 group by e1 ORDER BY e4"); //$NON-NLS-1$
+    }
+    
+    @Test public void testOrderByExpression() {
+    	Query query = (Query)helpResolve("select pm1.g1.e1 from pm1.g1 order by e2 || e3 "); //$NON-NLS-1$
+    	assertEquals(-1, query.getOrderBy().getExpressionPosition(0));
+    }
+    
+    @Test public void testOrderByExpression1() {
+    	Query query = (Query)helpResolve("select pm1.g1.e1 || e2 from pm1.g1 order by pm1.g1.e1 || e2 "); //$NON-NLS-1$
+    	assertEquals(0, query.getOrderBy().getExpressionPosition(0));
+    }
+    
+    @Test public void testOrderByExpression2() {
+    	helpResolveException("select pm1.g1.e1 from pm1.g1 union select pm1.g2.e1 from pm1.g2 order by pm1.g1.e1 || 2", "ORDER BY expression '(pm1.g1.e1 || 2)' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testOrderByConstantFails() {
+    	helpResolveException("select pm1.g1.e1 from pm1.g1 order by 2"); //$NON-NLS-1$
+    }
+    
+    @Test public void testCorrelatedNestedTableReference() {
+    	helpResolve("select pm1.g1.e1 from pm1.g1, table (exec pm1.sq2(pm1.g1.e2)) x"); //$NON-NLS-1$
+    	helpResolveException("select pm1.g1.e1 from pm1.g1, (exec pm1.sq2(pm1.g1.e2)) x"); //$NON-NLS-1$
+    }
+    
+    @Test public void testCorrelatedTextTable() {
+    	Command command = helpResolve("select x.* from pm1.g1, texttable(e1 COLUMNS x string) x"); //$NON-NLS-1$
+    	assertEquals(1, command.getProjectedSymbols().size());
+    }
+    
+    @Test public void testQueryString() throws Exception {
+    	helpResolveException("select querystring(xmlparse(document '<a/>'))");
+    }
+    
+	// validating AssignmentStatement, ROWS_UPDATED element assigned
+    @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure9() 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 + "ROWS_UPDATED = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
+        procedure = procedure + "ROWS_UPDATED =0;\n";         //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+        
+        helpResolveUpdateProcedure(procedure, userUpdateStr);
+    }
+
+	CreateUpdateProcedureCommand helpResolveUpdateProcedure(String procedure,
+			String userUpdateStr) throws QueryParserException,
+			QueryResolverException, TeiidComponentException,
+			QueryMetadataException {
+		FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+
+        ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
+        QueryResolver.resolveCommand(userCommand, metadata);
+        
+        return (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, AnalysisRecord.createNonRecordingRecord());
+	}
+    
+	// validating AssignmentStatement, variable type and assigned type 
+	// do not match
+    @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure10() 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 + "var1 = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
+        procedure = procedure + "ROWS_UPDATED =0;\n";         //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+        
+		helpResolveUpdateProcedure(procedure, userUpdateStr);
+    }
+    
+    //return should be first, then out
+    @Test public void testParamOrder() {
+        Query resolvedQuery = (Query)helpResolve("SELECT * FROM (exec pm4.spRetOut()) as a", RealMetadataFactory.exampleBQTCached(), null); //$NON-NLS-1$
+        
+        assertEquals("A.ret", resolvedQuery.getProjectedSymbols().get(0).getName());
+    }
+    
+    @Test public void testOrderByAggregatesError() throws Exception {
+    	helpResolveException("select count(*) from pm1.g1 order by e1");
+    }
+    
+    @Test public void testWithDuplidateName() {
+    	helpResolveException("with x as (TABLE pm1.g1), x as (TABLE pm1.g2) SELECT * from x");
+    }
+    
+    @Test public void testWithColumns() {
+    	helpResolveException("with x (a, b) as (TABLE pm1.g1) SELECT * from x");
+    }
+    
+    @Test public void testWithNameMatchesFrom() {
+    	helpResolve("with x as (TABLE pm1.g1) SELECT * from (TABLE x) x");
+    }
+    
+	// variables cannot be used among insert elements
+    @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure23() 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 + "Update pm1.g1 SET pm1.g1.e2 =1 , var1 = 2;\n"; //$NON-NLS-1$
+        procedure = procedure + "ROWS_UPDATED =0;\n";         //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
+
+        helpResolveUpdateProcedure(procedure, userQuery);
+	}
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha2/hibernate-dialect/pom.xml
===================================================================
--- trunk/hibernate-dialect/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/hibernate-dialect/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/hibernate-dialect/pom.xml (from rev 2804, trunk/hibernate-dialect/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/hibernate-dialect/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/hibernate-dialect/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/jboss-integration/pom.xml
===================================================================
--- trunk/jboss-integration/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/jboss-integration/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/jboss-integration/pom.xml (from rev 2804, trunk/jboss-integration/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/jboss-integration/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/jboss-integration/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,595 +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.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="Clear the caches in the system for a VDB", params={@ManagementParameter(name="cacheType",description="Type of Cache"), @ManagementParameter(name="vdbName",description="VDB Name"), at ManagementParameter(name="version",description="VDB Version")}, impact=Impact.ReadOnly)
-	public void clearCache(String cacheType, String vdbName, int version) {
-		this.dqpCore.clearCache(cacheType, vdbName, version);
-	}	
-	
-	@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.3.0.Alpha2/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java (from rev 2802, trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,601 @@
+/*
+ * 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;
+				}
+    		}
+    	}
+    	
+    	this.csr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
+    	DQP dqpProxy = proxyService(DQP.class, this.dqpCore, LogConstants.CTX_DQP);
+    	this.csr.registerClientService(DQP.class, dqpProxy, LogConstants.CTX_DQP);
+    	Admin adminProxy = proxyService(Admin.class, admin, LogConstants.CTX_ADMIN_API);
+    	this.csr.registerClientService(Admin.class, adminProxy, LogConstants.CTX_ADMIN_API);
+    	
+    	ClientServiceRegistryImpl jdbcCsr = new ClientServiceRegistryImpl();
+    	jdbcCsr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
+    	jdbcCsr.registerClientService(DQP.class, dqpProxy, LogConstants.CTX_DQP);
+    	
+    	if (this.jdbcSocketConfiguration.getEnabled()) {
+	    	this.jdbcSocket = new SocketListener(this.jdbcSocketConfiguration, jdbcCsr, 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$
+    	}
+    	
+    	ClientServiceRegistryImpl adminCsr = new ClientServiceRegistryImpl(Type.Admin);
+    	adminCsr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
+    	adminCsr.registerClientService(Admin.class, adminProxy, LogConstants.CTX_ADMIN_API);
+    	
+    	if (this.adminSocketConfiguration.getEnabled()) {
+	    	this.adminSocket = new SocketListener(this.adminSocketConfiguration, adminCsr, 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, 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="Clear the caches in the system for a VDB", params={@ManagementParameter(name="cacheType",description="Type of Cache"), @ManagementParameter(name="vdbName",description="VDB Name"), at ManagementParameter(name="version",description="VDB Version")}, impact=Impact.ReadOnly)
+	public void clearCache(String cacheType, String vdbName, int version) {
+		this.dqpCore.clearCache(cacheType, vdbName, version);
+	}	
+	
+	@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.3.0.Alpha2/metadata/pom.xml
===================================================================
--- trunk/metadata/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/metadata/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/metadata/pom.xml (from rev 2804, trunk/metadata/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/metadata/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/metadata/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/pom.xml
===================================================================
--- trunk/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/pom.xml (from rev 2804, trunk/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2</connection>
+		<developerConnection>scm:svn:https://svn.jboss.org/repos/teiid/tags/teiid-parent-7.3.0.Alpha2</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.3.0.Alpha2/runtime/pom.xml
===================================================================
--- trunk/runtime/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/runtime/pom.xml (from rev 2804, trunk/runtime/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/runtime/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/CommonsLogManagerAdapter.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/logging/CommonsLogManagerAdapter.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/CommonsLogManagerAdapter.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,128 +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.logging;
-
-import org.apache.commons.logging.Log;
-
-
-/**
- * This class is bridge for hooking LogManager into systems that use apache commons logging. In the Teiid
- * JBoss cache/Jboss Transactions use commons logging. This class used in "commons-logging.properties" file.
- */
-public class CommonsLogManagerAdapter implements Log {
-	String context;
-	
-    public CommonsLogManagerAdapter(String context) {
-        this.context = context;
-    }
-	
-	@Override
-	public void debug(Object arg0) {
-		LogManager.log(MessageLevel.DETAIL, this.context, arg0);
-	}
-
-	@Override
-	public void debug(Object arg0, Throwable arg1) {
-		LogManager.log(MessageLevel.DETAIL, this.context, arg1, arg0);
-	}
-
-	@Override
-	public void error(Object arg0) {
-		LogManager.log(MessageLevel.ERROR, this.context, arg0);
-	}
-
-	@Override
-	public void error(Object arg0, Throwable arg1) {
-		LogManager.log(MessageLevel.ERROR, this.context, arg1, arg0);
-	}
-
-	@Override
-	public void fatal(Object arg0) {
-		LogManager.log(MessageLevel.CRITICAL, this.context, arg0);
-	}
-
-	@Override
-	public void fatal(Object arg0, Throwable arg1) {
-		LogManager.log(MessageLevel.CRITICAL, this.context, arg1, arg0);
-	}
-
-	@Override
-	public void info(Object arg0) {
-		LogManager.log(MessageLevel.INFO, this.context, arg0);
-	}
-
-	@Override
-	public void info(Object arg0, Throwable arg1) {
-		LogManager.log(MessageLevel.INFO, this.context, arg1, arg0);
-	}
-
-	@Override
-	public void trace(Object arg0) {
-		LogManager.log(MessageLevel.TRACE, this.context, arg0);
-	}
-
-	@Override
-	public void trace(Object arg0, Throwable arg1) {
-		LogManager.log(MessageLevel.TRACE, this.context, arg1, arg0);
-	}
-
-	@Override
-	public void warn(Object arg0) {
-		LogManager.log(MessageLevel.WARNING, this.context, arg0);
-	}
-
-	@Override
-	public void warn(Object arg0, Throwable arg1) {
-		LogManager.log(MessageLevel.WARNING, this.context, arg1, arg0);
-	}
-	
-	@Override
-	public boolean isDebugEnabled() {
-		return LogManager.isMessageToBeRecorded(this.context, MessageLevel.DETAIL);
-	}
-
-	@Override
-	public boolean isErrorEnabled() {
-		return LogManager.isMessageToBeRecorded(this.context, MessageLevel.ERROR);
-	}
-
-	@Override
-	public boolean isFatalEnabled() {
-		return LogManager.isMessageToBeRecorded(this.context, MessageLevel.CRITICAL);
-	}
-
-	@Override
-	public boolean isInfoEnabled() {
-		return LogManager.isMessageToBeRecorded(this.context, MessageLevel.INFO);
-	}
-
-	@Override
-	public boolean isTraceEnabled() {
-		return LogManager.isMessageToBeRecorded(this.context, MessageLevel.TRACE);
-	}
-
-	@Override
-	public boolean isWarnEnabled() {
-		return LogManager.isMessageToBeRecorded(this.context, MessageLevel.WARNING);
-	}
-}

Deleted: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/Log4jListener.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/logging/Log4jListener.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/Log4jListener.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,118 +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.logging;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-
-
-/**
- * Log4J Listener
- */
-public class Log4jListener implements org.teiid.logging.Logger {
-	
-	@Override
-	public boolean isEnabled(String context, int level) {
-    	if ( context == null ) {
-            return false;
-        }
-    	Level logLevel = convert2Log4JLevel(level);
-        if ( logLevel == Level.OFF) {
-            return false;
-        }
-        Logger log = getLogger(context);
-        return log.isEnabledFor(logLevel);
-	}
-
-	@Override
-	public void log(int level, String context, Object msg) {
-		Logger log4j = getLogger(context);
-		log4j.log(convert2Log4JLevel(level), msg);
-	}
-
-	public void log(int level, String context, Throwable t, Object msg) {
-		Logger log4j = getLogger(context);
-		log4j.log(convert2Log4JLevel(level), msg, t);
-	}
-	
-	/**
-	 * Convert {@link MessageLevel} to {@link Level}
-	 * @param level
-	 * @return
-	 */
-    public static Level convert2Log4JLevel(int level) {
-    	switch (level) {
-    	case MessageLevel.CRITICAL:
-    		return Level.FATAL;
-    	case MessageLevel.ERROR:
-    		return Level.ERROR;
-    	case MessageLevel.WARNING:
-    		return Level.WARN;
-    	case MessageLevel.INFO:
-    		return Level.INFO;
-    	case MessageLevel.DETAIL:
-    	case MessageLevel.TRACE:
-    		return Level.DEBUG;
-    	case MessageLevel.NONE:
-    		return Level.OFF;
-    	}
-    	return Level.DEBUG;
-    }		
-    
-	/**
-	 * Convert  {@link Level} to {@link MessageLevel}
-	 * @param level
-	 * @return
-	 */
-    public static int convert2MessageLevel(Level level) {
-    	switch (level.toInt()) {
-    	case Level.FATAL_INT:
-    		return MessageLevel.CRITICAL;
-    	case Level.ERROR_INT:
-    		return MessageLevel.ERROR;
-    	case Level.WARN_INT:
-    		return MessageLevel.WARNING;
-    	case Level.INFO_INT:
-    		return MessageLevel.INFO;
-    	case Level.DEBUG_INT:
-    		return MessageLevel.DETAIL; 
-    	case Level.OFF_INT:
-    		return MessageLevel.NONE;
-    	}
-    	return MessageLevel.DETAIL;
-    }	    
-    
-    /**
-     * Get the logger for the given context.
-     * @param context
-     * @return
-     */
-	public static Logger getLogger(String context) {
-		return Logger.getLogger(context);
-	}  
-					
-	@Override
-	public void shutdown() {
-	}
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/Log4jListener.java (from rev 2802, trunk/runtime/src/main/java/org/teiid/logging/Log4jListener.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/Log4jListener.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/logging/Log4jListener.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,119 @@
+/*
+ * 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.logging;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+
+
+/**
+ * Log4J Listener
+ */
+public class Log4jListener implements org.teiid.logging.Logger {
+	
+	@Override
+	public boolean isEnabled(String context, int level) {
+    	if ( context == null ) {
+            return false;
+        }
+    	Level logLevel = convert2Log4JLevel(level);
+        if ( logLevel == Level.OFF) {
+            return false;
+        }
+        Logger log = getLogger(context);
+        return log.isEnabledFor(logLevel);
+	}
+
+	@Override
+	public void log(int level, String context, Object msg) {
+		Logger log4j = getLogger(context);
+		log4j.log(convert2Log4JLevel(level), msg);
+	}
+
+	public void log(int level, String context, Throwable t, Object msg) {
+		Logger log4j = getLogger(context);
+		log4j.log(convert2Log4JLevel(level), msg, t);
+	}
+	
+	/**
+	 * Convert {@link MessageLevel} to {@link Level}
+	 * @param level
+	 * @return
+	 */
+    public static Level convert2Log4JLevel(int level) {
+    	switch (level) {
+    	case MessageLevel.CRITICAL:
+    		return Level.FATAL;
+    	case MessageLevel.ERROR:
+    		return Level.ERROR;
+    	case MessageLevel.WARNING:
+    		return Level.WARN;
+    	case MessageLevel.INFO:
+    		return Level.INFO;
+    	case MessageLevel.DETAIL:
+    		return Level.DEBUG;
+    	case MessageLevel.TRACE:
+    		return Level.TRACE;
+    	case MessageLevel.NONE:
+    		return Level.OFF;
+    	}
+    	return Level.DEBUG;
+    }		
+    
+	/**
+	 * Convert  {@link Level} to {@link MessageLevel}
+	 * @param level
+	 * @return
+	 */
+    public static int convert2MessageLevel(Level level) {
+    	switch (level.toInt()) {
+    	case Level.FATAL_INT:
+    		return MessageLevel.CRITICAL;
+    	case Level.ERROR_INT:
+    		return MessageLevel.ERROR;
+    	case Level.WARN_INT:
+    		return MessageLevel.WARNING;
+    	case Level.INFO_INT:
+    		return MessageLevel.INFO;
+    	case Level.DEBUG_INT:
+    		return MessageLevel.DETAIL; 
+    	case Level.OFF_INT:
+    		return MessageLevel.NONE;
+    	}
+    	return MessageLevel.DETAIL;
+    }	    
+    
+    /**
+     * Get the logger for the given context.
+     * @param context
+     * @return
+     */
+	public static Logger getLogger(String context) {
+		return Logger.getLogger(context);
+	}  
+					
+	@Override
+	public void shutdown() {
+	}
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,374 +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.services;
-
-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.Properties;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-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.adminapi.VDB;
-import org.teiid.adminapi.VDB.ConnectionType;
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.client.security.InvalidSessionException;
-import org.teiid.client.security.SessionToken;
-import org.teiid.core.util.ArgCheck;
-import org.teiid.deployers.VDBRepository;
-import org.teiid.dqp.internal.process.DQPCore;
-import org.teiid.dqp.service.SessionService;
-import org.teiid.dqp.service.SessionServiceException;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.net.ServerConnection;
-import org.teiid.net.TeiidURL;
-import org.teiid.runtime.RuntimePlugin;
-import org.teiid.security.Credentials;
-import org.teiid.security.SecurityHelper;
-
-
-/**
- * This class serves as the primary implementation of the Session Service.
- */
- at ManagementObject(name="SessionService", componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
-public class SessionServiceImpl implements SessionService {
-	public static final String SECURITY_DOMAINS = "securitydomains"; //$NON-NLS-1$
-	
-	/*
-	 * Configuration state
-	 */
-    private long sessionMaxLimit = DEFAULT_MAX_SESSIONS;
-	private long sessionExpirationTimeLimit = DEFAULT_SESSION_EXPIRATION;
-	
-	/*
-	 * Injected state
-	 */
-	private VDBRepository vdbRepository;
-    private SecurityHelper securityHelper;
-
-    private DQPCore dqp;
-
-    private Map<String, SessionMetadata> sessionCache = new ConcurrentHashMap<String, SessionMetadata>();
-    private Timer sessionMonitor = new Timer("SessionMonitor", true); //$NON-NLS-1$
-    private LinkedList<String> securityDomains = new LinkedList<String>();
-    private LinkedList<String> adminSecurityDomains = new LinkedList<String>();
-    
-    
-    // -----------------------------------------------------------------------------------
-    // S E R V I C E - R E L A T E D M E T H O D S
-    // -----------------------------------------------------------------------------------
-
-    private void monitorSessions() {
-		long currentTime = System.currentTimeMillis();
-		for (SessionMetadata info : sessionCache.values()) {
-			try {
-    			if (!info.isEmbedded() && currentTime - info.getLastPingTime() > ServerConnection.PING_INTERVAL * 5) {
-    				LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.keepaliveFailed", info.getSessionId())); //$NON-NLS-1$
-    				closeSession(info.getSessionId());
-    			} else if (sessionExpirationTimeLimit > 0 && currentTime - info.getCreatedTime() > sessionExpirationTimeLimit) {
-    				LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.expireSession", info.getSessionId())); //$NON-NLS-1$
-    				closeSession(info.getSessionId());
-    			}
-			} catch (Exception e) {
-				LogManager.logDetail(LogConstants.CTX_SECURITY, e, "error running session monitor, unable to monitor: " + info.getSessionId()); //$NON-NLS-1$
-			}
-		}
-	}
-
-	@Override
-	public void closeSession(String sessionID) throws InvalidSessionException {
-		LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"closeSession", sessionID}); //$NON-NLS-1$
-		SessionMetadata info = this.sessionCache.remove(sessionID);
-		if (info == null) {
-			throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
-		}
-		if (info.getVDBName() != null) {
-            try {
-    			dqp.terminateSession(info.getSessionId());
-            } catch (Exception e) {
-                LogManager.logWarning(LogConstants.CTX_SECURITY,e,"Exception terminitating session"); //$NON-NLS-1$
-            }
-		}
-
-        // try to log out of the context.
-        try {
-        	LoginContext context = info.getLoginContext();
-        	if (context != null) {
-        		context.logout();
-        	}
-		} catch (LoginException e) {
-			 LogManager.logWarning(LogConstants.CTX_SECURITY,e,"Exception terminitating session"); //$NON-NLS-1$
-		}
-	}
-	
-	@Override
-	public SessionMetadata createSession(String userName, Credentials credentials, String applicationName, Properties properties, boolean adminConnection, boolean authenticate) 
-		throws LoginException, SessionServiceException {
-		ArgCheck.isNotNull(applicationName);
-        ArgCheck.isNotNull(properties);
-        
-        LoginContext loginContext = null;
-        String securityDomain = "none"; //$NON-NLS-1$
-        Object securityContext = null;
-        List<String> domains = this.securityDomains;
-        if (adminConnection) {
-        	domains = this.adminSecurityDomains;
-        }
-        
-        // Validate VDB and version if logging on to server product...
-        VDBMetaData vdb = null;
-        String vdbName = properties.getProperty(TeiidURL.JDBC.VDB_NAME);
-        if (vdbName != null) {
-        	String vdbVersion = properties.getProperty(TeiidURL.JDBC.VDB_VERSION);
-        	vdb = getActiveVDB(vdbName, vdbVersion);
-        }
-
-        if (sessionMaxLimit > 0 && getActiveSessionsCount() >= sessionMaxLimit) {
-            throw new SessionServiceException(RuntimePlugin.Util.getString("SessionServiceImpl.reached_max_sessions", new Object[] {new Long(sessionMaxLimit)})); //$NON-NLS-1$
-        }
-        
-        if (!domains.isEmpty() && authenticate) {
-	        // Authenticate user...
-	        // if not authenticated, this method throws exception
-        	boolean onlyAllowPassthrough = Boolean.valueOf(properties.getProperty(TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION, "false")); //$NON-NLS-1$
-	        TeiidLoginContext membership = authenticate(userName, credentials, applicationName, domains, this.securityHelper, onlyAllowPassthrough);
-	        loginContext = membership.getLoginContext();
-	        userName = membership.getUserName();
-	        securityDomain = membership.getSecurityDomain();
-	        securityContext = membership.getSecurityContext();
-        }        
-        
-        long creationTime = System.currentTimeMillis();
-
-        // Return a new session info object
-        SessionMetadata newSession = new SessionMetadata();
-        newSession.setSessionToken(new SessionToken(userName));
-        newSession.setSessionId(newSession.getSessionToken().getSessionID());
-        newSession.setUserName(userName);
-        newSession.setCreatedTime(creationTime);
-        newSession.setApplicationName(applicationName);
-        newSession.setClientHostName(properties.getProperty(TeiidURL.CONNECTION.CLIENT_HOSTNAME));
-        newSession.setIPAddress(properties.getProperty(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS));
-        newSession.setSecurityDomain(securityDomain);
-        if (vdb != null) {
-	        newSession.setVDBName(vdb.getName());
-	        newSession.setVDBVersion(vdb.getVersion());
-        }
-        
-        // these are local no need for monitoring.
-        newSession.setLoginContext(loginContext);
-        newSession.setSecurityContext(securityContext);
-        newSession.setVdb(vdb);
-        LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Logon successful for \"", userName, "\" - created SessionID \"", "" + newSession.getSessionToken().getSessionID(), "\"" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        this.sessionCache.put(newSession.getSessionId(), newSession);
-        return newSession;
-	}
-
-	VDBMetaData getActiveVDB(String vdbName, String vdbVersion) throws SessionServiceException {
-		VDBMetaData vdb = null;
-		
-		// handle the situation when the version is part of the vdb name.
-		
-		int firstIndex = vdbName.indexOf('.');
-		int lastIndex = vdbName.lastIndexOf('.');
-		if (firstIndex != -1) {
-			if (firstIndex != lastIndex || vdbVersion != null) {
-				throw new SessionServiceException(RuntimePlugin.Util.getString("ambigious_name", vdbName, vdbVersion)); //$NON-NLS-1$
-			}
-			vdbVersion = vdbName.substring(firstIndex+1);
-			vdbName = vdbName.substring(0, firstIndex);
-		}
-		
-		try {
-			if (vdbVersion == null) {
-				vdbVersion = "latest"; //$NON-NLS-1$
-				vdb = this.vdbRepository.getVDB(vdbName);
-			}
-			else {
-				vdb = this.vdbRepository.getVDB(vdbName, Integer.parseInt(vdbVersion));
-			}         
-		} catch (NumberFormatException e) {
-			throw new SessionServiceException(e, RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._3", vdbVersion)); //$NON-NLS-1$
-		}
-		
-		if (vdb == null) {
-			throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._1", vdbName, vdbVersion)); //$NON-NLS-1$
-		}
-		
-		if (vdb.getStatus() != VDB.Status.ACTIVE) {
-			throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._2", vdbName, vdbVersion)); //$NON-NLS-1$
-		}
-		if (vdb.getConnectionType() == ConnectionType.NONE) {
-			throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._4", vdbName, vdbVersion)); //$NON-NLS-1$
-		}
-		return vdb;
-	}
-
-	protected TeiidLoginContext authenticate(String userName, Credentials credentials, String applicationName, List<String> domains, SecurityHelper helper, boolean onlyallowPassthrough)
-			throws LoginException {
-		TeiidLoginContext membership = new TeiidLoginContext(helper);
-        membership.authenticateUser(userName, credentials, applicationName, domains, onlyallowPassthrough);                        
-		return membership;
-	}
-	
-	@Override
-	public Collection<SessionMetadata> getActiveSessions() throws SessionServiceException {
-		return new ArrayList<SessionMetadata>(this.sessionCache.values());
-	}
-	
-	@Override
-	public SessionMetadata getActiveSession(String sessionID) {
-		return this.sessionCache.get(sessionID);
-	}	
-
-	@Override
-	public int getActiveSessionsCount() throws SessionServiceException{
-		return this.sessionCache.size();
-	}
-
-	@Override
-	public Collection<SessionMetadata> getSessionsLoggedInToVDB(String VDBName, int vdbVersion)
-			throws SessionServiceException {
-		if (VDBName == null || vdbVersion <= 0) {
-			return Collections.emptyList();
-		}
-		ArrayList<SessionMetadata> results = new ArrayList<SessionMetadata>();
-		for (SessionMetadata info : this.sessionCache.values()) {
-			if (VDBName.equalsIgnoreCase(info.getVDBName()) && vdbVersion == info.getVDBVersion()) {
-				results.add(info);
-			}
-		}
-		return results;
-	}
-
-	@Override
-	public void pingServer(String sessionID) throws InvalidSessionException {
-		SessionMetadata info = getSessionInfo(sessionID);
-		info.setLastPingTime(System.currentTimeMillis());
-		this.sessionCache.put(sessionID, info);
-	}
-
-	@Override
-	public boolean terminateSession(String terminatedSessionID, String adminSessionID) {
-		Object[] params = {adminSessionID, terminatedSessionID};
-		LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.terminateSession", params)); //$NON-NLS-1$
-		try {
-			closeSession(terminatedSessionID);
-			return true;
-		} catch (InvalidSessionException e) {
-			LogManager.logWarning(LogConstants.CTX_SECURITY,e,RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", new Object[] {e.getMessage()})); //$NON-NLS-1$
-			return false;
-		}
-	}
-
-	@Override
-	public SessionMetadata validateSession(String sessionID) throws InvalidSessionException, SessionServiceException {
-		SessionMetadata info = getSessionInfo(sessionID);
-		return info;
-	}
-
-	private SessionMetadata getSessionInfo(String sessionID)
-			throws InvalidSessionException {
-		if (sessionID == null) {
-			throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
-		}
-		SessionMetadata info = this.sessionCache.get(sessionID);
-		if (info == null) {
-			throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
-		}
-		return info;
-	}
-	
-	@ManagementProperty (description="Maximum number of sessions allowed by the system (default 5000)")
-	public long getSessionMaxLimit() {
-		return this.sessionMaxLimit;
-	}
-	
-	public void setSessionMaxLimit(long limit) {
-		this.sessionMaxLimit = limit;
-	}
-	
-	@ManagementProperty(description="Max allowed time before the session is terminated by the system, 0 indicates unlimited (default 0)")
-	public long getSessionExpirationTimeLimit() {
-		return this.sessionExpirationTimeLimit;
-	}
-	
-	public void setSessionExpirationTimeLimit(long limit) {
-		this.sessionExpirationTimeLimit = limit;
-	}	
-	
-	public void setSecurityDomains(String domainNameOrder) {
-        if (domainNameOrder != null && domainNameOrder.trim().length()>0) {
-        	LogManager.logInfo(LogConstants.CTX_SECURITY, "Security Enabled: true"); //$NON-NLS-1$
-
-	        String[] domainNames = domainNameOrder.split(","); //$NON-NLS-1$
-	        for (String domainName : domainNames) {
-	            this.securityDomains.addLast(domainName);
-	        }
-        }		
-	}
-	
-	public void setAdminSecurityDomain(String domain) {
-		this.adminSecurityDomains.add(domain);
-		LogManager.logInfo(LogConstants.CTX_SECURITY, "Admin Security Enabled: true"); //$NON-NLS-1$
-	}
-
-	public void start() {
-        this.sessionMonitor.schedule(new TimerTask() {
-        	@Override
-        	public void run() {
-        		monitorSessions();
-        	}
-        }, 0, ServerConnection.PING_INTERVAL * 5);
-	}
-
-	public void stop(){
-		this.sessionMonitor.cancel();
-		this.sessionCache.clear();
-	}
-
-	public void setVDBRepository(VDBRepository repo) {
-		this.vdbRepository = repo;
-	}
-	
-	public void setSecurityHelper(SecurityHelper securityHelper) {
-		this.securityHelper = securityHelper;
-	}
-	
-	public void setDqp(DQPCore dqp) {
-		this.dqp = dqp;
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java (from rev 2802, trunk/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,375 @@
+/*
+ * 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.services;
+
+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.Properties;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+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.adminapi.VDB;
+import org.teiid.adminapi.VDB.ConnectionType;
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.client.security.InvalidSessionException;
+import org.teiid.client.security.SessionToken;
+import org.teiid.core.util.ArgCheck;
+import org.teiid.deployers.VDBRepository;
+import org.teiid.dqp.internal.process.DQPCore;
+import org.teiid.dqp.service.SessionService;
+import org.teiid.dqp.service.SessionServiceException;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.net.ServerConnection;
+import org.teiid.net.TeiidURL;
+import org.teiid.runtime.RuntimePlugin;
+import org.teiid.security.Credentials;
+import org.teiid.security.SecurityHelper;
+
+
+/**
+ * This class serves as the primary implementation of the Session Service.
+ */
+ at ManagementObject(name="SessionService", componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
+public class SessionServiceImpl implements SessionService {
+	public static final String SECURITY_DOMAINS = "securitydomains"; //$NON-NLS-1$
+	
+	/*
+	 * Configuration state
+	 */
+    private long sessionMaxLimit = DEFAULT_MAX_SESSIONS;
+	private long sessionExpirationTimeLimit = DEFAULT_SESSION_EXPIRATION;
+	
+	/*
+	 * Injected state
+	 */
+	private VDBRepository vdbRepository;
+    private SecurityHelper securityHelper;
+
+    private DQPCore dqp;
+
+    private Map<String, SessionMetadata> sessionCache = new ConcurrentHashMap<String, SessionMetadata>();
+    private Timer sessionMonitor = new Timer("SessionMonitor", true); //$NON-NLS-1$
+    private LinkedList<String> securityDomains = new LinkedList<String>();
+    private LinkedList<String> adminSecurityDomains = new LinkedList<String>();
+    
+    
+    // -----------------------------------------------------------------------------------
+    // S E R V I C E - R E L A T E D M E T H O D S
+    // -----------------------------------------------------------------------------------
+
+    private void monitorSessions() {
+		long currentTime = System.currentTimeMillis();
+		for (SessionMetadata info : sessionCache.values()) {
+			try {
+    			if (!info.isEmbedded() && currentTime - info.getLastPingTime() > ServerConnection.PING_INTERVAL * 5) {
+    				LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.keepaliveFailed", info.getSessionId())); //$NON-NLS-1$
+    				closeSession(info.getSessionId());
+    			} else if (sessionExpirationTimeLimit > 0 && currentTime - info.getCreatedTime() > sessionExpirationTimeLimit) {
+    				LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.expireSession", info.getSessionId())); //$NON-NLS-1$
+    				closeSession(info.getSessionId());
+    			}
+			} catch (Exception e) {
+				LogManager.logDetail(LogConstants.CTX_SECURITY, e, "error running session monitor, unable to monitor:", info.getSessionId()); //$NON-NLS-1$
+			}
+		}
+	}
+
+	@Override
+	public void closeSession(String sessionID) throws InvalidSessionException {
+		LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"closeSession", sessionID}); //$NON-NLS-1$
+		SessionMetadata info = this.sessionCache.remove(sessionID);
+		if (info == null) {
+			throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
+		}
+		if (info.getVDBName() != null) {
+            try {
+    			dqp.terminateSession(info.getSessionId());
+            } catch (Exception e) {
+                LogManager.logWarning(LogConstants.CTX_SECURITY,e,"Exception terminitating session"); //$NON-NLS-1$
+            }
+		}
+
+        // try to log out of the context.
+        try {
+        	LoginContext context = info.getLoginContext();
+        	if (context != null) {
+        		context.logout();
+        	}
+		} catch (LoginException e) {
+			 LogManager.logWarning(LogConstants.CTX_SECURITY,e,"Exception terminitating session"); //$NON-NLS-1$
+		}
+	}
+	
+	@Override
+	public SessionMetadata createSession(String userName, Credentials credentials, String applicationName, Properties properties, boolean adminConnection, boolean authenticate) 
+		throws LoginException, SessionServiceException {
+		ArgCheck.isNotNull(applicationName);
+        ArgCheck.isNotNull(properties);
+        
+        LoginContext loginContext = null;
+        String securityDomain = "none"; //$NON-NLS-1$
+        Object securityContext = null;
+        List<String> domains = this.securityDomains;
+        if (adminConnection) {
+        	domains = this.adminSecurityDomains;
+        }
+        
+        // Validate VDB and version if logging on to server product...
+        VDBMetaData vdb = null;
+        String vdbName = properties.getProperty(TeiidURL.JDBC.VDB_NAME);
+        if (vdbName != null) {
+        	String vdbVersion = properties.getProperty(TeiidURL.JDBC.VDB_VERSION);
+        	vdb = getActiveVDB(vdbName, vdbVersion);
+        }
+
+        if (sessionMaxLimit > 0 && getActiveSessionsCount() >= sessionMaxLimit) {
+            throw new SessionServiceException(RuntimePlugin.Util.getString("SessionServiceImpl.reached_max_sessions", new Object[] {new Long(sessionMaxLimit)})); //$NON-NLS-1$
+        }
+        
+        if (!domains.isEmpty() && authenticate) {
+	        // Authenticate user...
+	        // if not authenticated, this method throws exception
+        	boolean onlyAllowPassthrough = Boolean.valueOf(properties.getProperty(TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION, "false")); //$NON-NLS-1$
+	        TeiidLoginContext membership = authenticate(userName, credentials, applicationName, domains, this.securityHelper, onlyAllowPassthrough);
+	        loginContext = membership.getLoginContext();
+	        userName = membership.getUserName();
+	        securityDomain = membership.getSecurityDomain();
+	        securityContext = membership.getSecurityContext();
+        }        
+        
+        long creationTime = System.currentTimeMillis();
+
+        // Return a new session info object
+        SessionMetadata newSession = new SessionMetadata();
+        newSession.setSessionToken(new SessionToken(userName));
+        newSession.setSessionId(newSession.getSessionToken().getSessionID());
+        newSession.setUserName(userName);
+        newSession.setCreatedTime(creationTime);
+        newSession.setApplicationName(applicationName);
+        newSession.setClientHostName(properties.getProperty(TeiidURL.CONNECTION.CLIENT_HOSTNAME));
+        newSession.setIPAddress(properties.getProperty(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS));
+        newSession.setSecurityDomain(securityDomain);
+        if (vdb != null) {
+	        newSession.setVDBName(vdb.getName());
+	        newSession.setVDBVersion(vdb.getVersion());
+        }
+        
+        // these are local no need for monitoring.
+        newSession.setLoginContext(loginContext);
+        newSession.setSecurityContext(securityContext);
+        newSession.setVdb(vdb);
+        LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Logon successful for \"", userName, "\" - created SessionID \"", newSession.getSessionToken().getSessionID(), "\"" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        this.sessionCache.put(newSession.getSessionId(), newSession);
+        return newSession;
+	}
+
+	VDBMetaData getActiveVDB(String vdbName, String vdbVersion) throws SessionServiceException {
+		VDBMetaData vdb = null;
+		
+		// handle the situation when the version is part of the vdb name.
+		
+		int firstIndex = vdbName.indexOf('.');
+		int lastIndex = vdbName.lastIndexOf('.');
+		if (firstIndex != -1) {
+			if (firstIndex != lastIndex || vdbVersion != null) {
+				throw new SessionServiceException(RuntimePlugin.Util.getString("ambigious_name", vdbName, vdbVersion)); //$NON-NLS-1$
+			}
+			vdbVersion = vdbName.substring(firstIndex+1);
+			vdbName = vdbName.substring(0, firstIndex);
+		}
+		
+		try {
+			if (vdbVersion == null) {
+				vdbVersion = "latest"; //$NON-NLS-1$
+				vdb = this.vdbRepository.getVDB(vdbName);
+			}
+			else {
+				vdb = this.vdbRepository.getVDB(vdbName, Integer.parseInt(vdbVersion));
+			}         
+		} catch (NumberFormatException e) {
+			throw new SessionServiceException(e, RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._3", vdbVersion)); //$NON-NLS-1$
+		}
+		
+		if (vdb == null) {
+			throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._1", vdbName, vdbVersion)); //$NON-NLS-1$
+		}
+		
+		if (vdb.getStatus() != VDB.Status.ACTIVE) {
+			throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._2", vdbName, vdbVersion)); //$NON-NLS-1$
+		}
+		if (vdb.getConnectionType() == ConnectionType.NONE) {
+			throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._4", vdbName, vdbVersion)); //$NON-NLS-1$
+		}
+		return vdb;
+	}
+
+	protected TeiidLoginContext authenticate(String userName, Credentials credentials, String applicationName, List<String> domains, SecurityHelper helper, boolean onlyallowPassthrough)
+			throws LoginException {
+		TeiidLoginContext membership = new TeiidLoginContext(helper);
+        membership.authenticateUser(userName, credentials, applicationName, domains, onlyallowPassthrough);                        
+		return membership;
+	}
+	
+	@Override
+	public Collection<SessionMetadata> getActiveSessions() throws SessionServiceException {
+		return new ArrayList<SessionMetadata>(this.sessionCache.values());
+	}
+	
+	@Override
+	public SessionMetadata getActiveSession(String sessionID) {
+		return this.sessionCache.get(sessionID);
+	}	
+
+	@Override
+	public int getActiveSessionsCount() throws SessionServiceException{
+		return this.sessionCache.size();
+	}
+
+	@Override
+	public Collection<SessionMetadata> getSessionsLoggedInToVDB(String VDBName, int vdbVersion)
+			throws SessionServiceException {
+		if (VDBName == null || vdbVersion <= 0) {
+			return Collections.emptyList();
+		}
+		ArrayList<SessionMetadata> results = new ArrayList<SessionMetadata>();
+		for (SessionMetadata info : this.sessionCache.values()) {
+			if (VDBName.equalsIgnoreCase(info.getVDBName()) && vdbVersion == info.getVDBVersion()) {
+				results.add(info);
+			}
+		}
+		return results;
+	}
+
+	@Override
+	public void pingServer(String sessionID) throws InvalidSessionException {
+		SessionMetadata info = getSessionInfo(sessionID);
+		info.setLastPingTime(System.currentTimeMillis());
+		this.sessionCache.put(sessionID, info);
+		LogManager.logDetail(LogConstants.CTX_SECURITY, "Keep-alive ping received for session:", sessionID); //$NON-NLS-1$
+	}
+
+	@Override
+	public boolean terminateSession(String terminatedSessionID, String adminSessionID) {
+		Object[] params = {adminSessionID, terminatedSessionID};
+		LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.terminateSession", params)); //$NON-NLS-1$
+		try {
+			closeSession(terminatedSessionID);
+			return true;
+		} catch (InvalidSessionException e) {
+			LogManager.logWarning(LogConstants.CTX_SECURITY,e,RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", new Object[] {e.getMessage()})); //$NON-NLS-1$
+			return false;
+		}
+	}
+
+	@Override
+	public SessionMetadata validateSession(String sessionID) throws InvalidSessionException, SessionServiceException {
+		SessionMetadata info = getSessionInfo(sessionID);
+		return info;
+	}
+
+	private SessionMetadata getSessionInfo(String sessionID)
+			throws InvalidSessionException {
+		if (sessionID == null) {
+			throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
+		}
+		SessionMetadata info = this.sessionCache.get(sessionID);
+		if (info == null) {
+			throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
+		}
+		return info;
+	}
+	
+	@ManagementProperty (description="Maximum number of sessions allowed by the system (default 5000)")
+	public long getSessionMaxLimit() {
+		return this.sessionMaxLimit;
+	}
+	
+	public void setSessionMaxLimit(long limit) {
+		this.sessionMaxLimit = limit;
+	}
+	
+	@ManagementProperty(description="Max allowed time before the session is terminated by the system, 0 indicates unlimited (default 0)")
+	public long getSessionExpirationTimeLimit() {
+		return this.sessionExpirationTimeLimit;
+	}
+	
+	public void setSessionExpirationTimeLimit(long limit) {
+		this.sessionExpirationTimeLimit = limit;
+	}	
+	
+	public void setSecurityDomains(String domainNameOrder) {
+        if (domainNameOrder != null && domainNameOrder.trim().length()>0) {
+        	LogManager.logInfo(LogConstants.CTX_SECURITY, "Security Enabled: true"); //$NON-NLS-1$
+
+	        String[] domainNames = domainNameOrder.split(","); //$NON-NLS-1$
+	        for (String domainName : domainNames) {
+	            this.securityDomains.addLast(domainName);
+	        }
+        }		
+	}
+	
+	public void setAdminSecurityDomain(String domain) {
+		this.adminSecurityDomains.add(domain);
+		LogManager.logInfo(LogConstants.CTX_SECURITY, "Admin Security Enabled: true"); //$NON-NLS-1$
+	}
+
+	public void start() {
+        this.sessionMonitor.schedule(new TimerTask() {
+        	@Override
+        	public void run() {
+        		monitorSessions();
+        	}
+        }, 0, ServerConnection.PING_INTERVAL * 5);
+	}
+
+	public void stop(){
+		this.sessionMonitor.cancel();
+		this.sessionCache.clear();
+	}
+
+	public void setVDBRepository(VDBRepository repo) {
+		this.vdbRepository = repo;
+	}
+	
+	public void setSecurityHelper(SecurityHelper securityHelper) {
+		this.securityHelper = securityHelper;
+	}
+	
+	public void setDqp(DQPCore dqp) {
+		this.dqp = dqp;
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistry.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/ClientServiceRegistry.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistry.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,35 +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 org.teiid.core.ComponentNotFoundException;
-import org.teiid.security.SecurityHelper;
-
-
-public interface ClientServiceRegistry {
-	
-	<T> T getClientService(Class<T> iface) throws ComponentNotFoundException;
-	
-	SecurityHelper getSecurityHelper();
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistry.java (from rev 2802, trunk/runtime/src/main/java/org/teiid/transport/ClientServiceRegistry.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistry.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistry.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,39 @@
+/*
+ * 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 org.teiid.core.ComponentNotFoundException;
+import org.teiid.security.SecurityHelper;
+
+
+public interface ClientServiceRegistry {
+	
+	public enum Type {
+		ODBC, JDBC, Admin
+	}
+	
+	<T> T getClientService(Class<T> iface) throws ComponentNotFoundException;
+	
+	SecurityHelper getSecurityHelper();
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistryImpl.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/ClientServiceRegistryImpl.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistryImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,87 +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.util.HashMap;
-
-import org.teiid.core.ComponentNotFoundException;
-import org.teiid.core.util.ReflectionHelper;
-import org.teiid.runtime.RuntimePlugin;
-import org.teiid.security.SecurityHelper;
-
-
-public class ClientServiceRegistryImpl implements ClientServiceRegistry {
-
-	public static class ClientService {
-		private Object instance;
-		private String loggingContext;
-		private ReflectionHelper reflectionHelper;
-		
-		public ClientService(Object instance, String loggingContext,
-				ReflectionHelper reflectionHelper) {
-			this.instance = instance;
-			this.loggingContext = loggingContext;
-			this.reflectionHelper = reflectionHelper;
-		}
-		
-		public Object getInstance() {
-			return instance;
-		}
-		public String getLoggingContext() {
-			return loggingContext;
-		}
-		public ReflectionHelper getReflectionHelper() {
-			return reflectionHelper;
-		}
-	}
-	
-    private HashMap<String, ClientService> clientServices = new HashMap<String, ClientService>();
-    private SecurityHelper securityHelper;
-
-    public <T> T getClientService(Class<T> iface) throws ComponentNotFoundException {
-    	ClientService cs = getClientService(iface.getName());
-    	return iface.cast(cs.getInstance());
-    }
-    
-	public ClientService getClientService(String iface) throws ComponentNotFoundException {
-		ClientService cs = clientServices.get(iface);
-		if (cs == null) {
-			throw new ComponentNotFoundException(RuntimePlugin.Util.getString("ServerWorkItem.Component_Not_Found", iface)); //$NON-NLS-1$
-		}
-		return cs;
-	}
-
-	public <T> void registerClientService(Class<T> iface, T instance, String loggingContext) {
-		this.clientServices.put(iface.getName(), new ClientService(instance, loggingContext, new ReflectionHelper(iface)));
-	}	
-	
-	@Override
-	public SecurityHelper getSecurityHelper() {
-		return this.securityHelper;
-	}
-	
-	public void setSecurityHelper(SecurityHelper securityHelper) {
-		this.securityHelper = securityHelper;
-	}
-		
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistryImpl.java (from rev 2802, trunk/runtime/src/main/java/org/teiid/transport/ClientServiceRegistryImpl.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistryImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ClientServiceRegistryImpl.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,96 @@
+/*
+ * 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.util.HashMap;
+
+import org.teiid.core.ComponentNotFoundException;
+import org.teiid.core.util.ReflectionHelper;
+import org.teiid.runtime.RuntimePlugin;
+import org.teiid.security.SecurityHelper;
+
+
+public class ClientServiceRegistryImpl implements ClientServiceRegistry {
+	
+	public static class ClientService {
+		private Object instance;
+		private String loggingContext;
+		private ReflectionHelper reflectionHelper;
+		
+		public ClientService(Object instance, String loggingContext,
+				ReflectionHelper reflectionHelper) {
+			this.instance = instance;
+			this.loggingContext = loggingContext;
+			this.reflectionHelper = reflectionHelper;
+		}
+		
+		public Object getInstance() {
+			return instance;
+		}
+		public String getLoggingContext() {
+			return loggingContext;
+		}
+		public ReflectionHelper getReflectionHelper() {
+			return reflectionHelper;
+		}
+	}
+	
+    private HashMap<String, ClientService> clientServices = new HashMap<String, ClientService>();
+    private SecurityHelper securityHelper;
+    private Type type = Type.JDBC;
+    
+    public ClientServiceRegistryImpl() {
+    	
+    }
+    
+    public ClientServiceRegistryImpl(Type type) {
+    	this.type = type;
+	}
+
+    public <T> T getClientService(Class<T> iface) throws ComponentNotFoundException {
+    	ClientService cs = getClientService(iface.getName());
+    	return iface.cast(cs.getInstance());
+    }
+    
+	public ClientService getClientService(String iface) throws ComponentNotFoundException {
+		ClientService cs = clientServices.get(iface);
+		if (cs == null) {
+			throw new ComponentNotFoundException(RuntimePlugin.Util.getString("ServerWorkItem.Component_Not_Found", type, iface)); //$NON-NLS-1$
+		}
+		return cs;
+	}
+
+	public <T> void registerClientService(Class<T> iface, T instance, String loggingContext) {
+		this.clientServices.put(iface.getName(), new ClientService(instance, loggingContext, new ReflectionHelper(iface)));
+	}	
+	
+	@Override
+	public SecurityHelper getSecurityHelper() {
+		return this.securityHelper;
+	}
+	
+	public void setSecurityHelper(SecurityHelper securityHelper) {
+		this.securityHelper = securityHelper;
+	}
+		
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,67 +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 javax.net.ssl.SSLEngine;
-
-import org.jboss.netty.channel.ChannelPipeline;
-import org.jboss.netty.channel.DefaultChannelPipeline;
-import org.jboss.netty.handler.ssl.SslHandler;
-import org.teiid.common.buffer.StorageManager;
-import org.teiid.net.socket.ObjectChannel;
-import org.teiid.odbc.ODBCServerRemote;
-
-public class ODBCSocketListener extends SocketListener {
-	private ODBCServerRemote.AuthenticationType authType = ODBCServerRemote.AuthenticationType.CLEARTEXT;
-	
-	public ODBCSocketListener(SocketConfiguration config, ClientServiceRegistryImpl csr, StorageManager storageManager, int portOffset) {
-		super(config, csr, storageManager, portOffset);
-	}
-
-	@Override
-	protected SSLAwareChannelHandler createChannelPipelineFactory(final SSLConfiguration config, final StorageManager storageManager) {
-		return new SSLAwareChannelHandler(this, config, Thread.currentThread().getContextClassLoader(), storageManager) {
-			public ChannelPipeline getPipeline() throws Exception {
-				ChannelPipeline pipeline = new DefaultChannelPipeline();
-
-				SSLEngine engine = config.getServerSSLEngine();
-			    if (engine != null) {
-			        pipeline.addLast("ssl", new SslHandler(engine)); //$NON-NLS-1$
-			    }
-			    pipeline.addLast("odbcFrontendProtocol", new PgFrontendProtocol(1 << 20)); //$NON-NLS-1$
-			    pipeline.addLast("odbcBackendProtocol", new PgBackendProtocol()); //$NON-NLS-1$
-			    pipeline.addLast("handler", this); //$NON-NLS-1$
-			    return pipeline;
-			}			
-		};
-	}
-	
-	@Override
-	public ChannelListener createChannelListener(ObjectChannel channel) {
-		return new ODBCClientInstance(channel, this.authType);
-	}
-
-	public void setAuthenticationType(String value) {
-		this.authType = ODBCServerRemote.AuthenticationType.valueOf(value);
-	}
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java (from rev 2802, trunk/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,68 @@
+/*
+ * 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 javax.net.ssl.SSLEngine;
+
+import org.jboss.netty.channel.ChannelPipeline;
+import org.jboss.netty.channel.DefaultChannelPipeline;
+import org.jboss.netty.handler.ssl.SslHandler;
+import org.teiid.common.buffer.StorageManager;
+import org.teiid.net.socket.ObjectChannel;
+import org.teiid.odbc.ODBCServerRemote;
+
+public class ODBCSocketListener extends SocketListener {
+	private ODBCServerRemote.AuthenticationType authType = ODBCServerRemote.AuthenticationType.CLEARTEXT;
+	
+	public ODBCSocketListener(SocketConfiguration config, StorageManager storageManager, int portOffset) {
+		//the clientserviceregistry isn't actually used by ODBC 
+		super(config, new ClientServiceRegistryImpl(ClientServiceRegistry.Type.ODBC), storageManager, portOffset);
+	}
+
+	@Override
+	protected SSLAwareChannelHandler createChannelPipelineFactory(final SSLConfiguration config, final StorageManager storageManager) {
+		return new SSLAwareChannelHandler(this, config, Thread.currentThread().getContextClassLoader(), storageManager) {
+			public ChannelPipeline getPipeline() throws Exception {
+				ChannelPipeline pipeline = new DefaultChannelPipeline();
+
+				SSLEngine engine = config.getServerSSLEngine();
+			    if (engine != null) {
+			        pipeline.addLast("ssl", new SslHandler(engine)); //$NON-NLS-1$
+			    }
+			    pipeline.addLast("odbcFrontendProtocol", new PgFrontendProtocol(1 << 20)); //$NON-NLS-1$
+			    pipeline.addLast("odbcBackendProtocol", new PgBackendProtocol()); //$NON-NLS-1$
+			    pipeline.addLast("handler", this); //$NON-NLS-1$
+			    return pipeline;
+			}			
+		};
+	}
+	
+	@Override
+	public ChannelListener createChannelListener(ObjectChannel channel) {
+		return new ODBCClientInstance(channel, this.authType);
+	}
+
+	public void setAuthenticationType(String value) {
+		this.authType = ODBCServerRemote.AuthenticationType.valueOf(value);
+	}
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/commons-logging.properties
===================================================================
--- trunk/runtime/src/main/resources/commons-logging.properties	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/commons-logging.properties	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,2 +0,0 @@
-# overrides the logging in jboss cache and jboss transactions integration code
-org.apache.commons.logging.Log=org.teiid.logging.CommonsLogManagerAdapter
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/org/teiid/runtime/i18n.properties
===================================================================
--- trunk/runtime/src/main/resources/org/teiid/runtime/i18n.properties	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/org/teiid/runtime/i18n.properties	2010-12-24 19:07:00 UTC (rev 2805)
@@ -1,89 +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.
-#
-
-
-
-LocalBufferService.Failed_initializing_buffer_manager._8=Failed initializing buffer manager.
-
-VDBService.VDB_does_not_exist._1=VDB \"{0}\" version \"{1}\" does not exist.
-VDBService.VDB_does_not_exist._2=VDB \"{0}\" version \"{1}\" is not in the "active" status.
-VDBService.VDB_does_not_exist._4=VDB \"{0}\" version \"{1}\" is not accepting connections.
-VDBService.VDB_does_not_exist._3=Invalid VDB version \"{0}\" - must be a positive integer.
-
-# session service
-SessionServiceImpl.invalid_session=The specified session ID "{0}" is invalid. It cannot be found in the userbase.
-SessionServiceImpl.reached_max_sessions = The server has reached the maximum number of sessions of {0} as defined by the property "sessionMaxLimit".  If more sessions are required, modify this property value in the "teiid-jboss-beans.xml" file.
-SessionServiceImpl.expireSession = Expiring session {0}
-SessionServiceImpl.keepaliveFailed = Keepalive failed for session {0}
-SessionServiceImpl.The_username_0_and/or_password_are_incorrect=The username "{0}" and/or password and/or payload token could not be authenticated by any membership domain.
-SessionServiceImpl.terminateSession = Admin [{0}] is terminating this session: {1}.  
-
-no_passthrough_identity_found = Passthrough authentication failed. No authentication information found.
-
-
-ServerWorkItem.Received_exception_processing_request=Unexpected exception for session {0}
-ServerWorkItem.processing_error=Processing exception ''{0}'' for session {1}.  Exception type {2} thrown from {3}. Enable more detailed logging to see the entire stacktrace.
-ServerWorkItem.Component_Not_Found=Component not found: {0}
-
-SocketTransport.1=Bound to address {0} listening on port {1}
-LocalTransportHandler.Transport_shutdown=Tranport has been shutdown.
-SocketClientInstance.invalid_sessionkey=Invalid session key used during handshake
-SSLAwareChannelHandler.channel_closed=Channel closed
-
-invlaid_vdb_file=Invalid VDB file deployment failed {0}
-redeploying_vdb=Re-deploying VDB {0}
-validity_errors_in_vdb=VDB has validaity errors; failed to deploy - {0}
-vdb_save_failed=Failed to save metadata for VDB {0} 
-vdb_delete_failed=Failed to delete the cached metadata files due to:
-vdb_deployed=VDB "{0}" deployed in {1} state.
-vdb_undeployed=VDB "{0}" undeployed.
-system_vdb_load_error=System.vdb needs to be loaded before any other VDBs.
-fail_to_deploy="{0}" Can not be active because model "{1}" is not fully configured.
-failed_to_retrive_metadata="{0}" is now "incomplete", because model "{1}" can not retrieve metadata. Fix errors and re-deploy the VDB.
-invalid_metadata_file=Invalid metadata file found at {0}; delete this file and restart server.
-udf_model_not_found=User Defined Function (UDF) model "{0}" not found in the VDB
-duplicate_vdb=VDB with given name and version already exists! {0}.{1}
-system_vdb_not_found=System.vdb not found in classpath
-invalid_udf_file=No "path" information found to load the FUNCTION model {0}; FUNCTION model must have path information.
-failed_matadata_load=Failed to load metadata for VDB {0}.{1}
-vdb_not_found=VDB {0}.{1} not found deployed.
-translator_not_found=For {0}.{1} VDB, Translator "{2}" not found.
-recursive_delegation=For {0}.{1} VDB, recursive delegation {2} found.
-datasource_not_found=For {0}.{1} VDB, Data Source "{2}" not found.
-vdb_activated={0}.{1} status has been changed to active
-vdb_inactivated={0}.{1} status has been changed to inactive. Check the required translators and data sources!
-translator_added=Teiid translator "{0}" has been added.
-invalid_class={0} invalid type of class specified. Must be of type org.teiid.connector.api.Connector
-class_not_found=Class {0} not found.
-translator_removed=Teiid translator "{0}" removed.
-no_set_method=No {0} method found for translator property {1} 
-required_property_not_exists=Required property "{0}" has no value. Deployment is incomplete.
-name_not_found=Translator property "name" not defined for the deployment "{0}"
-translator_type_not_found=The parent translator defined not found in configuration "{0}"
-failed_to_load_odbc_metadata=Failed to load the ODBC metadata repository.
-no_active_connection=No active connection found
-bad_binding=Binding on a statement, that has not been prepared:{0}
-not_bound=No bound statement found with name {0}
-no_stmt_found=No prepared statement found with name {0}
-error_closing_stmt=Error closing portal statement {0}
-model_metadata_loading=VDB "{0}" - "{1}" model metadata is currently being loaded. Start Time: {2}
-ambigious_name=Ambiguous VDB name specified. Only single occurrence of the "." is allowed in the VDB name. Also, when version based vdb name is specified, then a separate "version" connection option is not allowed:{0}.{1} 

Copied: tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/org/teiid/runtime/i18n.properties (from rev 2802, trunk/runtime/src/main/resources/org/teiid/runtime/i18n.properties)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/org/teiid/runtime/i18n.properties	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/runtime/src/main/resources/org/teiid/runtime/i18n.properties	2010-12-24 19:07:00 UTC (rev 2805)
@@ -0,0 +1,89 @@
+#
+# 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.
+#
+
+
+
+LocalBufferService.Failed_initializing_buffer_manager._8=Failed initializing buffer manager.
+
+VDBService.VDB_does_not_exist._1=VDB \"{0}\" version \"{1}\" does not exist.
+VDBService.VDB_does_not_exist._2=VDB \"{0}\" version \"{1}\" is not in the "active" status.
+VDBService.VDB_does_not_exist._4=VDB \"{0}\" version \"{1}\" is not accepting connections.
+VDBService.VDB_does_not_exist._3=Invalid VDB version \"{0}\" - must be a positive integer.
+
+# session service
+SessionServiceImpl.invalid_session=The specified session ID "{0}" is invalid. It cannot be found in the userbase.
+SessionServiceImpl.reached_max_sessions = The server has reached the maximum number of sessions of {0} as defined by the property "sessionMaxLimit".  If more sessions are required, modify this property value in the "teiid-jboss-beans.xml" file.
+SessionServiceImpl.expireSession = Expiring session {0}
+SessionServiceImpl.keepaliveFailed = Keepalive failed for session {0}
+SessionServiceImpl.The_username_0_and/or_password_are_incorrect=The username "{0}" and/or password and/or payload token could not be authenticated by any membership domain.
+SessionServiceImpl.terminateSession = Admin [{0}] is terminating this session: {1}.  
+
+no_passthrough_identity_found = Passthrough authentication failed. No authentication information found.
+
+
+ServerWorkItem.Received_exception_processing_request=Unexpected exception for session {0}
+ServerWorkItem.processing_error=Processing exception ''{0}'' for session {1}.  Exception type {2} thrown from {3}. Enable more detailed logging to see the entire stacktrace.
+ServerWorkItem.Component_Not_Found=Only {0} connections are allowed on this port.  Component not found: {1}
+
+SocketTransport.1=Bound to address {0} listening on port {1}
+LocalTransportHandler.Transport_shutdown=Transport has been shutdown.
+SocketClientInstance.invalid_sessionkey=Invalid session key used during handshake
+SSLAwareChannelHandler.channel_closed=Channel closed
+
+invlaid_vdb_file=Invalid VDB file deployment failed {0}
+redeploying_vdb=Re-deploying VDB {0}
+validity_errors_in_vdb=VDB has validity errors; failed to deploy - {0}
+vdb_save_failed=Failed to save metadata for VDB {0} 
+vdb_delete_failed=Failed to delete the cached metadata files due to:
+vdb_deployed=VDB "{0}" deployed in {1} state.
+vdb_undeployed=VDB "{0}" undeployed.
+system_vdb_load_error=System.vdb needs to be loaded before any other VDBs.
+fail_to_deploy="{0}" Can not be active because model "{1}" is not fully configured.
+failed_to_retrive_metadata="{0}" is now "incomplete", because model "{1}" can not retrieve metadata. Fix errors and re-deploy the VDB.
+invalid_metadata_file=Invalid metadata file found at {0}; delete this file and restart server.
+udf_model_not_found=User Defined Function (UDF) model "{0}" not found in the VDB
+duplicate_vdb=VDB with given name and version already exists! {0}.{1}
+system_vdb_not_found=System.vdb not found in classpath
+invalid_udf_file=No "path" information found to load the FUNCTION model {0}; FUNCTION model must have path information.
+failed_matadata_load=Failed to load metadata for VDB {0}.{1}
+vdb_not_found=VDB {0}.{1} not found deployed.
+translator_not_found=For {0}.{1} VDB, Translator "{2}" not found.
+recursive_delegation=For {0}.{1} VDB, recursive delegation {2} found.
+datasource_not_found=For {0}.{1} VDB, Data Source "{2}" not found.
+vdb_activated={0}.{1} status has been changed to active
+vdb_inactivated={0}.{1} status has been changed to inactive. Check the required translators and data sources!
+translator_added=Teiid translator "{0}" has been added.
+invalid_class={0} invalid type of class specified. Must be of type org.teiid.connector.api.Connector
+class_not_found=Class {0} not found.
+translator_removed=Teiid translator "{0}" removed.
+no_set_method=No {0} method found for translator property {1} 
+required_property_not_exists=Required property "{0}" has no value. Deployment is incomplete.
+name_not_found=Translator property "name" not defined for the deployment "{0}"
+translator_type_not_found=The parent translator defined not found in configuration "{0}"
+failed_to_load_odbc_metadata=Failed to load the ODBC metadata repository.
+no_active_connection=No active connection found
+bad_binding=Binding on a statement, that has not been prepared:{0}
+not_bound=No bound statement found with name {0}
+no_stmt_found=No prepared statement found with name {0}
+error_closing_stmt=Error closing portal statement {0}
+model_metadata_loading=VDB "{0}" - "{1}" model metadata is currently being loaded. Start Time: {2}
+ambigious_name=Ambiguous VDB name specified. Only single occurrence of the "." is allowed in the VDB name. Also, when version based vdb name is specified, then a separate "version" connection option is not allowed:{0}.{1} 

Deleted: tags/teiid-parent-7.3.0.Alpha2/test-integration/common/pom.xml
===================================================================
--- trunk/test-integration/common/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/test-integration/common/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/test-integration/common/pom.xml (from rev 2804, trunk/test-integration/common/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/test-integration/common/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/test-integration/common/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/test-integration/db/pom.xml
===================================================================
--- trunk/test-integration/db/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/test-integration/db/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/test-integration/db/pom.xml (from rev 2804, trunk/test-integration/db/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/test-integration/db/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/test-integration/db/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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.3.0.Alpha2/test-integration/pom.xml
===================================================================
--- trunk/test-integration/pom.xml	2010-12-23 22:11:01 UTC (rev 2800)
+++ tags/teiid-parent-7.3.0.Alpha2/test-integration/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2-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.3.0.Alpha2/test-integration/pom.xml (from rev 2804, trunk/test-integration/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha2/test-integration/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha2/test-integration/pom.xml	2010-12-24 19:07:00 UTC (rev 2805)
@@ -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.3.0.Alpha2</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